-2

I am trying to format the date which is entered as a string using string tokenizer. Date format will be enter as

String str="18-AUG-92".

I am splitting it into

int ndate = Integer.parseInt(str.nextToken());
int nmonth = Integer.parseInt(str.nextToken());
int nyear = Integer.parseInt(str.nextToken());

But during nmonth it's showing error that entered value "AUG" is in string.

I want to convert "AUG" to 08.

Anybody know?

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
  • Use DateFormatter instead of stringtokenizer – Jens Apr 03 '19 at 04:39
  • Use the built in date parsing facilities. Use a `DateTimeFormatterBuilder` and its `parseCaseInsensitive` method to build a `DateTimeFormatter`. Parse into a `LocalDate`. This has methods for obtaining year, month and day of month as integers. The details are covered in many places. The linked questions may not be enough, use your search engine for the rest. Also `StringTokenizer` is legacy and not recmmended for new code. – Ole V.V. Apr 03 '19 at 04:58

1 Answers1

0

Here you are.

String datetime="18-Aug-92";
DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("dd-MMM-yy");
LocalDate date = LocalDate.parse(datetime, dateFormat);
System.out.println(date.getMonth().getValue());
  • Sure. have fixed the answer using DateTimeFormatter – Oleg Ashchepkov Apr 03 '19 at 05:03
  • Thanks. There are a couple of minor issues: month abbreviations are locale dependent, and the asker had `AUG` in all uppercase (which won’t work with your code). But you are basically showing the right classes to use, which is always helpful. – Ole V.V. Apr 03 '19 at 05:31
  • 1
    If you prefer, you may use the slightly briefer `date.getMonthValue()` for getting the 8 for August. – Ole V.V. Apr 03 '19 at 05:37