Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

java - How can I convert a date in YYYYMMDDHHMMSS format to epoch or unix time?

EDIT: I have edited my question to include more information, I have tried many ways to do this already, asking a question on StackOverflow is usually my last resort. Any help is greatly appreciated.

I have a date (which is a Timestamp object) in a format of YYYYMMDDHHMMSS (e.g. 20140430193247). This is sent from my services to the front end which displays it in the format: date:'dd/MM/yyyy' using AngularJS.

How can I convert this into Epoch/Unix time?

I have tried the duplicate question that is linked to this, what I get returned is a different date.

I have also tried the following:

A:

//_time == 20140430193247
return _time.getTime()/1000; // returns 20140430193 - INCORRECT

B:

return _time.getTime(); // returns 20140430193247 (Frontend: 23/03/2608) - INCORRECT

C:

Date date = new Date();
//_time = 20140501143245 (i.e. 05/01/2014 14:32:45)
String str = _time.toString();
System.out.println("Time string is " + str);
//Prints: Time string is 2608-03-24 15:39:03.245 meaning _time.toString() cannot be used
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
try {
        date = df.parse(str);
} catch (ParseException e) {
}

return date; // returns 20140501143245 - INCORRECT

D:

date = new java.sql.Date(_time.getTime());
return date; // returns 2608-03-24 - INCORRECT

The following shows the todays date correctly:

Date date = new Date();
return date; // returns 1398939384523 (Frontend: 01/05/2014)

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I got the answer after quite a while of trying different ways. The solution was pretty simple - to parse the time to a string as toString() didn't work.

    Date date;
    SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");

    try {
        date = df.parse(String.valueOf(_time.getTime()));
    } catch (ParseException e) {
        throw new RuntimeException("Failed to parse date: ", e);
    }

    return date.getTime();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...