Java~时间戳小知识

大叔对java时间戳使用的总结

  1. Java里的Date对象有方法setTime,主要是将一个时间戳转成一个日期对象,而这个时间戳的标准是unix标准,即当前时间与1970/1/1相差的毫秒数,记得是毫秒!
  2. .net里的时间戳与java不同,所有需要特殊处理一个它的其实时间,而且.net里时间戳为double,如何要给java传输,需要转为long!
  3. java与.net时间在进行传输时,不建议直接使用时间字符串,因为会有兼容问题,还是建议使用时间戳为标准.
  4. 开一个.net里的一个扩展方法,主要用来生成java的long类型及起始时间的时间戳
  5. 注意java里的setTime,使用的时间戳参数为UTC时间戳

C#里相关时间戳的扩展方法

    /// <summary>
/// 时间帮助类
/// </summary>
public class TimeHelper
{
/// <summary>
/// 日期转换成unix时间戳
/// </summary>
/// <param name="dateTime"></param>
/// <returns></returns>
public static long DateTimeToUnixTimestamp(DateTime dateTime)
{
var start = new DateTime(, , , , , , DateTimeKind.Local);
return Convert.ToInt64((dateTime - start).TotalMilliseconds);
} /// <summary>
/// unix时间戳转换成日期
/// </summary>
/// <param name="unixTimeStamp">时间戳(秒)</param>
/// <returns></returns>
public static DateTime UnixTimestampToDateTime(DateTime target, long timestamp)
{
var start = new DateTime(, , , , , , DateTimeKind.Local);
return start.AddSeconds(timestamp);
} }

在C#里为java传输时,需要把本地时间转为UTC时间

TimeHelper.DateTimeToUnixTimestamp(DateTime.Now.ToUniversalTime());

这样在java时,直接setTime后,就是本地时间了

    Date d1 = new Date();
d1.setTime(1490232651510L);
System.err.println(d1);

aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAWkAAABECAIAAADMXFNFAAAOaklEQVR4nO1b628c1RWfv4cIgRBfuqlUfwG1HyqqqpVoCwghMkbQpgIUlFKgoFKggqCFJITmHRKC83IMhCHEGPKw42f8fq13bWey3tn37uxrvI840w/jnZ29r7k7XnvX8fnpp2gyc8+5555772/uvTsWZEVDOAQAAAB2EHDtAAKBQFuCdgCBQCcE7QACgU4I2gEEAp0Q1Y7RCc/WpA4AAGpBRTtm/Ynxqbnx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0xDXDkl0oh02k5OpHcYmonJwg5WsYZ1frsjWJyWUmtcd9mWqC3C2Bc8nq0VYDDWfyAI2MeqlHVL1VwYYROxtZt2zeN26S6zMc07tII5Ur1SJweZXUsvQJ5TEjlrRzxmIFdF94l9DmNfoj8F86x3iz9K0p7y7P8r5KzlLJO2ADcuWwRq1o7y1Xv0JpkbtqDL3OtIO68dILt1bfdN2HBO+erL87kN8AxM/hbJW5OBLKuSrOf7Pq9BvwyQ0G1VR8X8pV+2B0CJKnOxTGMD9BfgmHQAAOAFoBwAAcALQDgAA4ASgHQAAwAlAOwAAgBOAdgAAACcA7QAAAE4A2gEAAJzg/5JgW86/LBnNAAAAAElFTkSuQmCC" alt="" />

感谢各位的阅读!

知识在于积累!

上一篇:python面试中被问的最多的10道题


下一篇:简单认识一下什么是vue-router