Parsing month-based strings in java

I am trying to parse a string that looks like this:

2015, 2, 31, 17, 0, 1 

so I decided that I would use

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

but he suggested that the months are based on 1. In this case, month (2) is March. How can I say SimpleDateFormat or any other class for analysis with zero months?

+6
source share
2 answers

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])); 
+4
source

One solution I can see in a month with

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

With calendar

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

By default, months is an index based on 0. cm.

Why is january month 0 in the java calendar?

Why months from one on Java SimpleDateFormat?

0
source

Source: https://habr.com/ru/post/984854/


All Articles