【问题标题】:Android time conversion安卓时间转换
【发布时间】:2019-03-14 00:02:36
【问题描述】:

我已完成以下代码将时间从 UTC 更改为另一个时区,但代码仅显示 UTC 时间。此外,在格式化为源时间格式后,它显示系统时区。

private String setTimezone(String time){
sourceformatter = new SimpleDateFormat("hh:mm a, E dd MMM yyyy");
dateFormatter = new SimpleDateFormat("hh:mm a");

sourceformatter.setTimeZone(TimeZone.getTimeZone("UTC"));
    Log.e("reicievedformat",time);
Date value = null;
try {
    value = sourceformatter.parse(time);
} catch (ParseException e) {
    e.printStackTrace();
}
Log.d("afterfirstformat",dateFormatter.format(value));
dateFormatter.setTimeZone(TimeZone.getTimeZone("IST"));
time =dateFormatter.format(value);
    Log.d("Finaltime",time);
return time;
}

输出:- 记录值

  • 电子/接收格式:2018 年 10 月 8 日星期一下午 12:36

  • D/afterfirstformat:下午 6:21

  • 晚/决赛时间:下午 12:36

如您所见,我将在 2018 年 10 月 8 日星期一(“UTC”)下午 12:36,我想转换为 IST,但最后一次 12:36 PM 似乎尚未转换.

【问题讨论】:

  • 嗨,欢迎来到堆栈溢出。现在你的要求是什么?能详细点吗?
  • 你期望的输出是什么
  • 2018 年 10 月 8 日星期一(“UTC”)下午 12:36,我想转换为 IST
  • 顺便考虑扔掉长期过时且臭名昭著的麻烦SimpleDateFormat和朋友,并将ThreeTenABP添加到您的Android项目中,以便使用java.time,现代Java日期和时间API .与它一起工作要好得多。 LocalDateTime.parse("12:36 PM, Mon 08 Oct 2018", DateTimeFormatter.ofPattern("hh:mm a, E dd MMM yyyy", Locale.ENGLISH)).atOffset(ZoneOffset.UTC).atZoneSameInstant(ZoneId.of("Asia/Kolkata")).format(DateTimeFormatter.ofPattern("hh:mm a", Locale.ENGLISH)).

标签: java android timezone simpledateformat datetime-conversion


【解决方案1】:

Java 中的 IST 代表“以色列标准时间”。 将此用于“印度标准时间”

dateFormatter.setTimeZone(TimeZone.getTimeZone("Asia/Kolkata"));

Java 中的日期和时间 API 让您头疼。 我通过Daniel Lew 使用这个库。 https://github.com/dlew/joda-time-android

【讨论】:

  • 如果您的系统时区是“IST”,请尝试将 IST 更改为另一个时区并与之匹配。
  • 在 java 中 IST 代表以色列标准时间
  • 在我的 Java IST 上被理解为 Atlantic/Reykjavik(冰岛标准时间还是夏季时间?)三个和四个字母的时区缩写通常是模棱两可的,它就像一盒巧克力,你不知道知道你会得到什么......(IST,继续这个例子,也可能意味着爱尔兰标准或夏令时)。
【解决方案2】:

试试这个

public static String getDateOut(String ourDate) {
        try
        {
            //be sure that passing date has same format as formatter
            SimpleDateFormat formatter = new SimpleDateFormat("hh:mm a, E dd MMM yyyy");
            formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
            Date value = formatter.parse(ourDate);

            SimpleDateFormat dateFormatter = new SimpleDateFormat("hh:mm a"); //this format changeable
            dateFormatter.setTimeZone(TimeZone.getTimeZone("IST"));
            ourDate = dateFormatter.format(value);

        }
        catch (Exception e)
        {
            ourDate = "00-00-0000 00:00";
        }
        return ourDate;
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多