简体   繁体   中英

How to convert and format a UTC datetime to local time

My program converts UTC time to localtime but not in the format that I want. I took an example from the following link Convert UTC to current locale time

 public static void main(String[] args) throws ParseException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
        Date myDate = simpleDateFormat.parse("2015-08-19 05:30:00.049 UTC+0000");
        System.out.println("**********myDate:" + myDate);
    }

Output:

**********myDate:Wed Aug 19 01:30:00 EDT 2015

My expected output format is:

2015-08-19 01:00:14

Please advise.

You parsed the text to a date successfully:

Date myDate = simpleDateFormat.parse("2015-08-19 05:30:00.049 UTC+0000");

However, you then proceeded to print myDate.toString() .

System.out.println("**********myDate:" + myDate);

You won't get your expected format that way. Use (another) SimpleDateFormat to format myDate the way you want

final SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm")
outputFormat.setTimeZone(TimeZone.getTimeZone("EDT"));
System.out.println("**********myDate:" + ouputFormat.format(myDate));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM