当前位置: 首页 > 面试题库 >

Java / Android-将GMT时间字符串转换为本地时间

冯风史
2023-03-14
问题内容

好的,所以我有一个字符串,说“ Tue May 21 14:32:00 GMT
2012”,我想将此字符串转换为本地时间,格式为2012年5月21日下午2:32。我尝试了SimpleDateFormat(“ MM dd,yyyy
hh:mm a”)。parse(),但它引发了异常。所以我该怎么做?

异常为“未报告的异常java.text.ParseException;必须捕获或声明为抛出”。

在行中 Date date = inputFormat.parse(inputText);

我在TextMate上运行的代码:

public class test{
    public static void main(String arg[]) {
        String inputText = "Tue May 22 14:52:00 GMT 2012";
        SimpleDateFormat inputFormat = new SimpleDateFormat(
            "EEE MMM dd HH:mm:ss 'GMT' yyyy", Locale.US);
        inputFormat.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
        SimpleDateFormat out = new SimpleDateFormat("MMM dd, yyyy h:mm a");
        Date date = inputFormat.parse(inputText);
        String output = out.format(date);
       System.out.println(output);
    }
}

问题答案:

您提供的用于 解析 的格式字符串与您实际获得的文本格式不匹配。您需要先解析,然后再格式化。看起来像您想要的:

SimpleDateFormat inputFormat = new SimpleDateFormat(
    "EEE MMM dd HH:mm:ss 'GMT' yyyy", Locale.US);
inputFormat.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));

SimpleDateFormat outputFormat = new SimpleDateFormat("MMM dd, yyyy h:mm a");
// Adjust locale and zone appropriately

Date date = inputFormat.parse(inputText);
String outputText = outputFormat.format(date);

编辑:这是简短但完整的程序形式的相同代码,并带有您的示例输入:

import html" target="_blank">java.util.*;
import java.text.*;

public class Test {
    public static void main(String[] args) throws ParseException {
        String inputText = "Tue May 21 14:32:00 GMT 2012";
        SimpleDateFormat inputFormat = new SimpleDateFormat
            ("EEE MMM dd HH:mm:ss 'GMT' yyyy", Locale.US);
        inputFormat.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));

        SimpleDateFormat outputFormat =
            new SimpleDateFormat("MMM dd, yyyy h:mm a");
        // Adjust locale and zone appropriately
        Date date = inputFormat.parse(inputText);
        String outputText = outputFormat.format(date);
        System.out.println(outputText);
    }
}

您可以编译并运行 该确切代码 吗?



 类似资料:
  • 对于国际化的程序,往往有如下的需求: 在某一时区A的用户向系统提交的数据被保存在了服务端的数据库中。同时,系统也保存了时区A的用户提交请求时的GMT。而在另一个时区B的用户要浏览时区A的用户录入的信息。但时间要显示成时区B的本地时间。 对于上面的需求,最简单的方法是将服务端保存的GMT直接转换成时区B的本地时间。对于Web系统。这个工作可以交给JavaScript来完成。也就是说,服务端将服务端保

  • JDK中提供了一个java.util.Date类,该类是Java中用来处理时间的类。在Date类中有很多和日期/时间相关的方法,如getDate、getDay等,但这些方法都是Date类的遗留产物,这些方法在以后的JDK版本中可以被去掉,因此,并不建议在程序中使用这些方法。不过Date类中有少数的方法不在这些方法之列,这些方法仍然可以在程序中放心地使用。其中getTime和setTime方法是经常

  • 我有以下字符串: 我尝试用以下代码将此字符串转换为: Java . time . format . datetimeparseexception:无法解析文本“18/07/2019 04:30:00”:无法从TemporalAccessor获取LocalDateTime 我错过了什么?

  • 我想将datetime-local从html转换为UTC时间: html: Java: 即本地时间(GMT 8),我想将其转换为UTC字符串时间 例如:转换为- 我搜索了很多资源,但仍然不知道怎么做。

  • 我正在尝试将pst时间戳转换为Java的gmt 我有一个时间戳为的字符串。我如何处理该字符串并将其转换为gmt时间戳? 我做了一些我想做的事,但还没去任何地方 结果是:

  • 我将要求用户输入一个特定时间:上午10点、下午12点30分、下午2点47分、上午1点09分、下午5点等。我将使用获取用户的输入。 如何将该解析/转换为对象?Java中是否有任何内置函数允许我这样做?