根据UTC格式转换日期和时间字符串

Lav*_*nya 12 time android date utc

我有一个日期字符串2012-11-21 13:11:25,我从本地数据库.我必须根据UTC设置进行转换并将其显示在特定屏幕上.所以如果GMT+05:30它应该显示2012-11-21 18:41:25在屏幕上.我该怎么做这个转换.我已经检查了一些问题但是没有成功.

我能够得到一个Date对象,返回类似Wed Nov 21 13:11:25 GMT+05:30 2012 之后我需要得到的时间18:41:25和日期11-21-2012

提前致谢

Kai*_*Kai 16

dfinputFmt必须使用相同的格式.

但我认为你应该这样做:

    Date myDate = new Date();

    Calendar calendar = Calendar.getInstance();
    calendar.setTimeZone(TimeZone.getTimeZone("UTC"));
    calendar.setTime(myDate);
    Date time = calendar.getTime();
    SimpleDateFormat outputFmt = new SimpleDateFormat("MMM dd, yyy h:mm a zz");
    String dateAsString = outputFmt.format(time);
    System.out.println(dateAsString);
Run Code Online (Sandbox Code Playgroud)


SAN*_*NAT 15

从当前时间获取UTC:

public String getCurrentUTC(){
        Date time = Calendar.getInstance().getTime();
        SimpleDateFormat outputFmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        outputFmt.setTimeZone(TimeZone.getTimeZone("UTC"));
        return outputFmt.format(time);
}
Run Code Online (Sandbox Code Playgroud)


Gur*_*yan 5

获取所需格式的日期格式化字符串的最佳方法是

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
String formatted = dateFormat.format(date);
Run Code Online (Sandbox Code Playgroud)