converting UTC date string to local date string inspecific format

陌路散爱 提交于 2020-01-07 00:36:13

问题


I have a UTC date in string

String utcDate = "2014-03-05 07:09:07.0";

I want to convert it to local date string of format DD-MMM-YYYY hh:mm a eg: 5-Mar-2014 12:39 PM from UTC date 2014-03-05 07:09:07.0

How this can be achieved using simple java or joda API


回答1:


Very easy to achieve with default functionality. I hope the local data is for display only.

SimpleDateFormat parser = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
parser.setTimeZone(TimeZone.getTimeZone("UTC"));
Date parsed = parser.parse(utcDate);

SimpleDateFormat formatter = new SimpleDateFormat("d-MMM-yyyy hh:mm a");
System.out.println(formatter.format(parsed));



回答2:


The java.util.Date and .Calendar classes are notoriously troublesome. Avoid them. Instead use either Joda-Time library or the new java.time package in bundled with Java 8.

If you use the ISO 8601 format of strings, you can pass the string directly to a Joda-Time DateTime constructor. Your input string is close, but the space in the middle should be a T.

Some example code using the Joda-Time 2.3 library.

String input = "2014-03-05 07:09:07.0";
String inputModified = input.replace( " ", "T" );

DateTimeZone timeZone = DateTimeZone.forID( "Europe/Paris" );
DateTime dateTimeUtc = new DateTime( inputModified, DateTimeZone.UTC );

DateTime dateTimeParis = dateTimeUTC.toZone( timeZone );
String outputFrance = DateTimeFormat.forPattern( "FF" ).withLocale(Locale.FRANCE).print( dateTimeParis );

DateTimeFormatter formatter = DateTimeFormat.forPattern( "d-MMM-yyyy hh:mm a" ).withLocale( Locale.US );
String outputParisCustom = formatter.print( dateTimeParis );



回答3:


Below code will help you to convert your UTC to IST or any other timezone. You need to pay attention to the timezone that you want to use with SimpleDateFormat.

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

public class ConvertTimeZone {
    public static void main(String args[]) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
        Date date = sdf.parse("2014-03-05 07:09:07");
        System.out.println("time in UTC " +sdf.format(date));
        sdf.setTimeZone(TimeZone.getTimeZone("IST"));
        System.out.println("Time in IST is " + sdf.format(date));
    }
}


来源:https://stackoverflow.com/questions/22192800/converting-utc-date-string-to-local-date-string-inspecific-format

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!