6

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?

JonatanSJ
  • 122
  • 7
  • is there a reason you cannot just add one to the month immediately before formatting it with the date format? That would seem like it would solve the problem. – Davis Broda Apr 08 '15 at 15:15
  • There are no placeholders for 0-based month in SimpleDateFormat, so you need to change month explicitly or create a date using Calendar. – Alex Salauyou Apr 08 '15 at 15:16
  • 2
    @DavisBroda: How would you expect that to work with the example given, which would be parsed as "February 31st" (and thus either adjusted or failing to parse). – Jon Skeet Apr 08 '15 at 15:17
  • @DavisBroda I am doing comparisons in java before sending the strings along to a javascript environment (which uses zero-based months), that's why I can't change the strings. – JonatanSJ Apr 08 '15 at 15:20
  • @JonSkeet Thinking it through in more detail, my vague idea would not work. It was based on a misunderstanding of what the question was asking. Thank you for pointing that out. – Davis Broda Apr 08 '15 at 16:02

2 Answers2

4

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]));
JonatanSJ
  • 122
  • 7
Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109
0

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?

Community
  • 1
  • 1
M Sach
  • 33,416
  • 76
  • 221
  • 314