Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/376.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java时区格式问题_Java_Timezone_Simpledateformat_Datetime Format_Timezone Offset - Fatal编程技术网

Java时区格式问题

Java时区格式问题,java,timezone,simpledateformat,datetime-format,timezone-offset,Java,Timezone,Simpledateformat,Datetime Format,Timezone Offset,应用程序中保存的时间以UTC为单位。应用程序的用户位于不同的时区,如PST、IST等 我的问题与中的问题非常相似。 我尝试实施那里提供的解决方案,但它似乎对我不起作用: Calendar calendar = Calendar.getInstance(); calendar.setTime(history.getCreatedTimestamp()); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); //H

应用程序中保存的时间以UTC为单位。应用程序的用户位于不同的时区,如PST、IST等

我的问题与中的问题非常相似。 我尝试实施那里提供的解决方案,但它似乎对我不起作用:

Calendar calendar = Calendar.getInstance();
calendar.setTime(history.getCreatedTimestamp());
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

//Here you say to java the initial timezone. This is the secret
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
//Will print in UTC
System.out.println(sdf.format(calendar.getTime()));

//Here you set to your timezone
sdf.setTimeZone(TimeZone.getDefault());
//Will print on your default Timezone
System.out.println(sdf.format(calendar.getTime()));

我建议您使用Java 8类(
SimpleDataFormat
Calendar
,如果可能,请避免使用它们):

不幸的是,像PST和IST这样的短区名称是不明确的(请检查),因此您需要将它们转换为(Java使用的标准,如
美国/洛杉矶
欧洲/伦敦


关于时区的更多信息:

为什么要将现有值转换为字符串,然后再次解析它?这几乎总是个坏主意。请提供一个演示问题的示例-这里缺少很多内容。此外,还不清楚您希望
ZoneOffset.of小时(Calendar.ZONE\u OFFSET)
做什么,但这基本上是错误的
Calendar.ZONE\u OFFSET
是一个常量-您肯定想使用用户的实际时区,它不太可能是
ZoneOffset
。“PST”不是一个时区——它是一个模棱两可的缩写,表示观察到时区时的一部分时间。您需要知道用户的实际时区ID,例如美国/纽约-或使用
ZoneId.systemDefault()
如果您的代码在用户的机器上运行-您的问题不清楚。否,代码将在位于PST的服务器上运行。参考此答案,可能位于太平洋时间。。。但无论如何,这意味着您需要从某处获取用户的时区。有吗?(此外,在展示代码时请更加小心。使用预览查看发布时我们将看到的内容,并问问自己这是否是索引等方面的最佳展示。)好的,但将hh改为hh为24小时,而不是12小时;这似乎是问题中的一个错误。@JoopEggen完成了!答案解释得很好,谢谢,但显然无法解决OP不知道服务器上的客户端时区的问题。
long timestamp = history.getCreatedTimestamp();
// create Instant from timestamp value
Instant instant = Instant.ofEpochMilli(timestamp);

// formatter
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

// convert to UTC
System.out.println(formatter.format(instant.atZone(ZoneOffset.UTC)));

// convert to another timezone
System.out.println(formatter.format(instant.atZone(ZoneId.of("America/Los_Angeles"))));

// convert to JVM default timezone
System.out.println(formatter.format(instant.atZone(ZoneId.systemDefault())));