sonam
sonam

Reputation: 905

Converting long (whose decimal representation represents a yyyyMMdd.. date) to a different date format

I have long of the form

20120720162145
yyyymmddhhmmss

I have to convert it to 2012-07-20 4:21 PM form. Is there any way in Java to do this using Date?

Upvotes: 2

Views: 1868

Answers (2)

Anonymous
Anonymous

Reputation: 86323

I should like to contribute the modern answer. The answer from 2012 is correct (if you accept 0:21 PM as a time, and otherwise it’s simple to change it to 12:21 PM). Today I prefer

    // convert your long into a LocalDateTime
    DateTimeFormatter uuuuMmDdHhMmSs = DateTimeFormatter.ofPattern("uuuuMMddHHmmss");
    long longDate = 20120720162145L;
    LocalDateTime dateTime = LocalDateTime.parse(String.valueOf(longDate), uuuuMmDdHhMmSs);

    // Format the LocalDateTime into your desired format
    DateTimeFormatter humanReadableFormatter
            = DateTimeFormatter.ofPattern("uuuu-MM-dd h:mm a", Locale.ENGLISH);
    String formattedDateTime = dateTime.format(humanReadableFormatter);
    System.out.println(formattedDateTime);

This prints the desired

2012-07-20 4:21 PM

I recommend you give explicit locale for formatting. I have given English since AM and PM are hardly used in other languages than English, but you choose.

I noticed that in your question you had two spaces between the date and the time in 2012-07-20 4:21 PM. If you want the hours space padded so they always take up two positions (nice if formatted date-times are presented under each other in a column), use pp pad modifier before the h:

    DateTimeFormatter humanReadableFormatter
            = DateTimeFormatter.ofPattern("uuuu-MM-dd pph:mm a", Locale.ENGLISH);

If you want to format into 20/07/2012 (as asked in this duplicate question):

    DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
    String formattedDate = dateTime.format(dateFormatter);

java.time

The classes Date, DateFormat and SimpleDateFormat used in the answer from 2012 are now long outdated and have also proven to be poorly designed. I recommend you leave them behind and instead use java.time, the modern Java date and time API.

Link: Oracle tutorial: Date Time explaining how to use java.time.

Upvotes: 0

aioobe
aioobe

Reputation: 421090

Here's how:

long input = 20120720162145L;

DateFormat inputDF = new SimpleDateFormat("yyyyMMddHHmmss");
DateFormat outputDF = new SimpleDateFormat("yyyy-MM-dd K:mm a");

Date date = inputDF.parse(""+input);

System.out.println(outputDF.format(date));

Output:

2012-07-20 4:21 PM

Upvotes: 8

Related Questions