java - Java 中的 C# 日期时间

标签 java c# timestamp-with-timezone

我正在尝试将毫秒转换为 Java 中的时间。

当我在 C# 中执行此操作时

DateTime EpochOrigin = new DateTime(1970, 1, 1, 0, 0, 0, 0);

Console.WriteLine("1406205185123 = " + EpochOrigin.AddMilliseconds(1406205185123));

结果2014年7月24日12:33:05

当我在 Java 中做同样的事情时

 Calendar cc = new GregorianCalendar();

cc.setTimeInMillis(1406205185123L);

结果 2014 年 7 月 24 日星期四 13:33:05 BST

Java 结果比 C# 多了 1 个小时。

有什么建议可以解决这个问题吗?

最佳答案

在 C# 中,DateTime 不存储时区信息,但有一个 Kind 属性,其值指示该实例表示的时间是否基于本地时间时间、协调世界时 (UTC) 或 neithee(请参阅 MSDN )。 DateTime.Kind 属性的默认值为Unspecified。因此,在您的 C# 代码中,使用以下行创建 DateTime 结构

DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);

绝对应该以这种方式创建:

DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

以便用作转换的引用时间(纪元时间原点为 1970 年 1 月 1 日 00:00 UTC)。

更多信息可以在上一个问题中找到:https://stackoverflow.com/a/2883645/1236452 .

编辑 1

简单说一下:C# 中的 DateTime 以某种方式知道时区(我的本地时间是 GMT+1)(编辑:请参阅评论并编辑2):

DateTime t = new DateTime(1970,1,1,0,0,0);
Console.WriteLine(t.ToLocalTime());      // 01/01/1970 01:00:00 (GMT+1)
Console.WriteLine(t.ToUniversalTime());  // 31/12/1969 23:00:00 (GMT)

编辑2

正如评论中正确指出的那样,DateTime 不知道时区,因为它保存时区信息。但是,在其 Kind 属性中,它确实存储了一个值,该值指示实例是基于本地时间还是基于 UTC,如 documentation 中所述。 :

DateTime.Kind Property: Gets a value that indicates whether the time represented by this instance is based on local time, Coordinated Universal Time (UTC), or neither. [...]

The Kind property allows a DateTime value to clearly reflect either Coordinated Universal Time (UTC) or the local time. In contrast, the DateTimeOffset structure can unambiguously reflect any time in any time zone as a single point in time.

关于java - Java 中的 C# 日期时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24938554/

相关文章:

oracle - oracle 如何在内部存储带时区的时间戳

java - 如何在 Netbeans 中排除 module-info.java (11)?

类似 Java Delphi 的类引用

c# - 如何从 C# 显示文件属性对话框安全选项卡

c# - ManualResetEvent 未始终如一地释放所有等待线程的问题

javascript - 使用 momentjs 在最终用户的时区进行操作

Azure 流分析输入损坏了包含时区信息的字符串

java - 在 Spring Controller 中使用 Callable 和 WebApplicationInitializer 获取 IllegalStateException

java - 套接字,BufferedWriter.flush()不发送数据

c# - WCF 客户端安全 header 错误 "An invalid security token was provided"