zoukankan      html  css  js  c++  java
  • 将 javascript 中的 timestamp(时间戳) 转 c# 的 datetime类型

      相信很多人在工作中都会遇到需要将 timestamp(时间戳) 转换为 datetime 类型,特别是做网站开发的时候,有时候需要将前端传递过来的 timestamp 转为 datetime 类型,而在转的过程中发现了需要注意的地方。

      首先先说说在 javascript 中产生 timestamp 的方式,一般有以下几种方式:

        var date = new Date();
        
        //获取timestamp
        var timestamp1 = date.getTime();
        var timestamp2 = Date.now();
        var timestamp3 = date.valueOf();
        
        //输出当前时间
        console.info("date.toString:",date.toString());
        console.info("date.toLocaleString:",date.toLocaleString());
        
        //输出时间戳
        console.info("date.getTime:",timestamp1);
        console.info("date.now:",timestamp2);
        console.info("date.valueOf:",timestamp3);

      

      我当前结果显示:

      

      然后在c#中需要将时间戳转换为timestamp(至于前端怎么传递数据到后端,不在此章范围):

        string timestampStr = "1481038051980";
        long timestamp = long.Parse(timestampStr);
        DateTime dt = new DateTime(1970,1,1,0,0,0).AddMilliseconds(timestamp);
        Console.WriteLine(dt);
    
        Console.ReadKey();

      然而,神奇的事情发生了,显示结果如下:

      

      不对啊,上面 js 产生的时间戳的时间是 2016/12/6 下午11:27:31 ( Tue Dec 06 2016 23:27:31 ) ,也就是说日期显示是对的,但时间不对, 一直在纠结,甚至怀疑是不是记错 js 时间戳的生成方式了,于是查文档,没错啊,那是怎么回事呢?最后突然想到,会不会和时区有关,于是加了一行代码:

        string timestampStr = "1481038051980";
        long timestamp = long.Parse(timestampStr);
        DateTime dt = new     DateTime(1970,1,1,0,0,0).AddMilliseconds(timestamp);
        Console.WriteLine(dt);
        Console.WriteLine(dt.ToLocalTime());

      是的,只需要调用 ToLocalTime() 方法,结果如下:

      

      就是这么简单,仅仅是个时区的问题

  • 相关阅读:
    【HTTP】长连接和短连接
    HTTP/1.1 持久连接 persistent connection
    浅谈Websocket、Ajax轮询和长轮询(long polling)
    web通信之跨文档通信 postMessage
    HTML5 postMessage 和 localStorage 实现窗口间通信
    CORS 和 JSONP
    【转】js中几种实用的跨域方法原理详解
    [跨域]前端解决跨域问题
    RFC1867 HTTP file upload
    Multipart/form-data POST文件上传
  • 原文地址:https://www.cnblogs.com/lhgohead/p/6139673.html
Copyright © 2011-2022 走看看