Android String date "2017-09-04T07:09:30.269+00:00" convert to long

216 Views Asked by At

I received the date string from the notification server in the following format. 2017-09-04T07:09:30.269+00:00

I want it to convert to long to save in database.

public static long convertStringDatetoLong(final String date, final String inputFormat) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(inputFormat);
        try {
            Date outputDate = simpleDateFormat.parse(date);
            return outputDate.getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 0;
    }

Then i call convertStringDatetoLong(date, "yyyy-mm-dd'T'HH:mm:ss.SSSXXX"); But i found that the convert long is somehow wrong.

The result time is 1483513770269 which is wrong. it should be sometimes like 1504509270911 which is start with 15... (which i got with currentTimeMillis)

2017-09-04T07:09:30.269+00:00, the input time zone is not the same as My time zone which is GMT+08:00

I don't know how to convert it to the device time zone and get the correct milliseconds to save.

Updated:

Sorry that i am doing stupid thing. it should be MM not mm.

2

There are 2 best solutions below

2
On

You can easily do this with the Object ZonedDateTime like this:

String example = "2017-09-04T07:09:30.269+00:00";
OffsetDateTime offset = OffsetDateTime.parse(example);
ZonedDateTime result = offset.atZoneSameInstant( ZoneId.systemDefault() ); // Put you wanted zone here

From there on you can easily get the timestamp as millis with this line of code:

Long timestamp = startTime.toInstant().getEpochSecond();
0
On

Try this,

String timeStr = "2017-09-04T07:09:30.269+00:00";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Date Obj= null;
try {
    Obj = sdf.parse(timeStr);
} catch (ParseException e) {
    e.printStackTrace();
}

long time = Obj.getTime();
System.out.println(time);