JonatanSJ
JonatanSJ

Reputation: 122

Parsing zero-based month strings in java

I am trying to parse a String that looks like:

2015, 2, 31, 17, 0, 1

so i figured I'll use

SimpleDateFormat("yyyy, MM, dd, hh, mm, ss")

but it assumed the months are 1-based. In this case the month (2) is March. How can i tell SimpleDateFormat or any other class to parse with zero-based months?

Upvotes: 6

Views: 665

Answers (3)

Basil Bourque
Basil Bourque

Reputation: 338644

java.time

Is modern Java, use java.time classes.

Add one to fix zero-based month

Split your input string into parts. Parse each part as an int integer number. For the second part (at index 1) you need to add one to correct the screwy zero-based counting.

java.time.LocalDateTime

Use the first three parts to make a LocalDate. Use the second three parts to make a LocalTime. Combine for a LocalDateTime object.

String input = "2015, 2, 31, 17, 0, 1";
String[] parts = input.split ( ", " );
LocalDate ld = LocalDate.of ( Integer.parseInt ( parts[ 0 ] ) , Integer.parseInt ( parts[ 1 ] ) + 1 , Integer.parseInt ( parts[ 2 ] ) );
LocalTime lt = LocalTime.of ( Integer.parseInt ( parts[ 3 ] ) , Integer.parseInt ( parts[ 4 ] ) , Integer.parseInt ( parts[ 5 ] ) );
LocalDateTime ldt = LocalDateTime.of ( ld , lt );

ldt.toString() = 2015-03-31T17:00:01

Determine a moment with time zone

By the way, this does not define a moment, does not determine a point on the timeline. For that you need the context of a time zone by which to interpret the date and the time-of-day.

ZoneId z = ZoneId.of ( "Pacific/Auckland" );  // NOT a moment.
ZonedDateTime zdt = ldt.atZone ( z );  // Now we have determined a moment.

zdt.toString() = 2015-03-31T17:00:01+13:00[Pacific/Auckland]

Upvotes: 1

Jordi Castilla
Jordi Castilla

Reputation: 26961

Use Calendar:

String[] yourString = "2015, 2, 31, 17, 0, 1".split(",");

Calendar c = new GregorianCalendar();
c.set(Calendar.YEAR, Integer.valueOf(yourString[0]));
c.set(Calendar.MONTH, Integer.valueOf(yourString[1]));
c.set(Calendar.DAY_OF_MONTH, Integer.valueOf(yourString[2]));
c.set(Calendar.HOUR_OF_DAY, Integer.valueOf(yourString[3]));
c.set(Calendar.MINUTE, Integer.valueOf(yourString[4]));
c.set(Calendar.SECOND, Integer.valueOf(yourString[5]));

Upvotes: 4

M Sach
M Sach

Reputation: 34424

One solution i can see increase one month with

Date newDate = DateUtils.addMonths(new Date(), 1);

With calendar

Calendar cal = Calendar.getInstance(); 
cal.add(Calendar.MONTH, 1);

By default months are 0 based index. see

Why is January month 0 in Java Calendar?

Why are months off by one with Java SimpleDateFormat?

Upvotes: 0

Related Questions