Hi,
How can I parse a date in the “yyyy-MM-dd HH:mm:ss” format into a long ?
I tried to use SimpleDateFormat class but it doesn’t implement the parse() method.
Thanks
Hello @camille23
To parse a date you want to use the Calendar class [1].
Because the regex library is too heavy for embedded systems you will have to retrieve the information in the String manually and then, use a Calendar instance to handle the conversion to long.
Here is an example:
String strDate = "2021-09-28 13:12:30";
Calendar cal = Calendar.getInstance();
int year = new Integer(strDate.substring(0, 4)).intValue();
int month = new Integer(strDate.substring(5, 7)).intValue();
int date = new Integer(strDate.substring(8, 10)).intValue();
int hourOfDay = new Integer(strDate.substring(11, 13)).intValue();
int minute = new Integer(strDate.substring(14, 16)).intValue();
int second = new Integer(strDate.substring(17, 19)).intValue();
// You can adjust TimeZone to your needs
cal.setTimeZone(TimeZone.getTimeZone("GMT+1:00"));
// MONTH is 0 based, an offset of -1 must be applied
cal.set(year, month - 1, date, hourOfDay, minute, second);
long parsedDate = cal.getTime().getTime();
[1] Calendar