SimpleDateFormat(“MM / dd / yy,HH:mm:ss zzz”)给出时区为GMT + 05:30

问题描述 投票:-1回答:3

我想像这样显示时间

09/07 / 18,23:15:00

我使用上面的timeformat但是显示时区的例子就像这个IST它的节目GMT+05:30。我使用下面的代码来解析日期: -

 fun parseDate(time: String?): String? {
    if (time != null) {
        val inputPattern = "yyyy-MM-dd'T'HH:mm:ss"
        val outputPattern = "MM/dd/yy, HH:mm:ss zzz"
        val inputFormat = SimpleDateFormat(inputPattern, Locale.getDefault())
        val outputFormat = SimpleDateFormat(outputPattern, Locale.getDefault())

        var date: Date? = null
        var str: String? = null

        try {
            date = inputFormat.parse(time)
            str = outputFormat.format(date)
        } catch (e: ParseException) {
            e.printStackTrace()
        }
        return str
    }

    return time
}

任何人都可以帮我解决这个问题。

android kotlin simpledateformat
3个回答
0
投票

根据Document https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html,您必须使用'z'而不是'zzz,并尝试为您的日期格式设置时区,如下所示。

 inputFormat.timeZone = TimeZone.getTimeZone("IST")

0
投票

根据文件应该是:“MM / dd / yy,HH:mm:ss zz”。这是两个'z'而不是3。

this other question你必须在TimeZone上设置SimpleDateFormat

来自:太平洋标准时间 zz:太平洋标准时间 zzz:GMT-08:00

但正如OP所说,三种替代方案可以提供相同的输出。

例:

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

public class HelloWorld{

 public static void main(String []args){
    SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yy, HH:mm:ss zz");
    Date date = new Date();
    sdf.setTimeZone(TimeZone.getTimeZone("IST"));
    String txtDate = sdf.format(date);
    System.out.println(txtDate);

    sdf = new SimpleDateFormat("MM/dd/yy, HH:mm:ss z");
    sdf.setTimeZone(TimeZone.getTimeZone("IST"));
    txtDate = sdf.format(date);
    System.out.println(txtDate);

    sdf = new SimpleDateFormat("MM/dd/yy, HH:mm:ss zzz");
    sdf.setTimeZone(TimeZone.getTimeZone("IST"));
    txtDate = sdf.format(date);
    System.out.println(txtDate);
 }
}

输出:

09/07/18, 18:26:08 IST
09/07/18, 18:26:08 IST
09/07/18, 18:26:08 IST

SimpleDateFormat formats


0
投票

你必须像这样设置你想要的时区

outputFormat.timeZone =  TimeZone.getTimeZone("Asia/Calcutta") // this is a unique identifier of "IST" 

示例:https://try.kotlinlang.org/#/UserProjects/ulc8sg2dslsbgt4qsauqd1a1sv/akvvttd16f1sqjcg6rm7smuh6p

© www.soinside.com 2019 - 2024. All rights reserved.