3

I am trying to convert a date in String format into UNIX timestamp, I am able to convert it but when I check the timestamp it displays incorrect date.

I am using the following code to convert a Date in String to Unix timestamp:

String selected_date = "16/11/2015 1:34 am";
        datetime.setText(selected_date);
        DateFormat dateFormat = new SimpleDateFormat("MM/dd/yy hh:mm a");
        Date date = null;
        try {
            date = dateFormat.parse(selected_date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        long unixTime = (long)date.getTime()/1000;

The output UNIX timestamp is: 1460309640

But when I convert that timestamp using a web tool it returns: 4/11/2016, 1:34:00 AM

1 Answer 1

5

The format

DateFormat dateFormat = new SimpleDateFormat("MM/dd/yy hh:mm a");

is not compatible with the string

String selected_date = "16/11/2015 1:34 am";

16 can't be a month!

2015 is not a year in two digits format

The right format seems to be (not sure if kk or KK depending on hours if 0 based or not)

DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy kk:mm a");
Sign up to request clarification or add additional context in comments.

5 Comments

In fact, it appears to be wrapping the date around. The output is 4/11/2016, which could be construed as the "16th month of 2015".
How do I make 2015 to 15?
yyyy for 2015, yy for 15
This code ignores the crucial issue of time zone.
@BasilBourque that is correct, but the original string to convert in a date is not considering it. So or the string must be changed in format or they don't need to know the time zone assuming that they are using the system time zone

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.