How to convert getTime() to 'YYYY-MM-DD HH24:M

2019-03-07 02:25发布

This question already has an answer here:

I Have the following code in my application

System.out.println(rec.getDateTrami().getTime());

I need to convert the following format (I suppose that they are seconds)

43782000
29382000
29382000

To a format YYYY-MM-DD HH24:MI:SS, anyone can help to me?

3条回答
男人必须洒脱
2楼-- · 2019-03-07 02:53

You could use SimpledateFormat.

new SimpleDateFormat("YYYY-MM-DD HH24:MI:SS").format(date)
查看更多
SAY GOODBYE
3楼-- · 2019-03-07 03:04

Use java.time

Best if you can change getDateTrami() to return an OffsetDateTime or ZonedDateTime from java.time. java.time is the modern Java date and time API. It is also known as JSR-310. The code is the same no matter which of the two mentioned types is returned:

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");
    System.out.println(rec.getDateTrami().format(formatter));

This prints a date and time like

2017-12-14 16:52:20

java.time is generally so much nicer to work with than the outmoded Date class and its friends.

If you cannot change the return type

I assume getDateTrami() returns a java.util.Date. Since the Date class is long outmoded, the first thing to do is to convert it to java.time.Instant. From there you perform your further operations:

    Date oldfashionedDateObject = rec.getDateTrami();
    ZonedDateTime dateTime = oldfashionedDateObject.toInstant()
            .atZone(ZoneId.of("Atlantic/Cape_Verde"));
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");
    System.out.println(dateTime.format(formatter));

The result is similar to the above, of course. I on purpose made explicit in which time zone I want to interpret the point in time. Please substitute your own if it doesn’t happen to be Atlantic/Cape_Verde.

Formatting seconds since the epoch

    int seconds = 29_382_000;
    ZonedDateTime dateTime = Instant.ofEpochSecond(seconds)
            .atZone(ZoneId.of("Atlantic/Cape_Verde"));
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");
    System.out.println(dateTime.format(formatter));

This snippet prints

1970-12-06 23:40:00

A date in December 1970. If this is incorrect, it is because 29 382 000 didn’t denote seconds since the epoch of January 1, 1970 at midnight in UTC, also known as the Unix epoch. This is by far the most common time to measure seconds from. If your seconds are measured from some other fixed point in time, I cannot guess which, and you have got a job to do to find out. Again decide which time zone you want to specify.

查看更多
成全新的幸福
4楼-- · 2019-03-07 03:05

You can make use of the SimpleDateFormat

Example:

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date date = new Date();
date.setTime(rec.getDateTrami().getTime());
System.out.println(format.format(date));

Documentation: SimpleDateFormat, DateFormat

查看更多
登录 后发表回答