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() 方法,结果如下:

      

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

  • 相关阅读:
    Swift中的参数内部名称和外部名称
    iOS 发布流程
    解决xcode iOS真机调试正常,模拟器失败问题
    iOS 解决ipv6问题
    cocos2dx 字体描边遇到的描边缺失的bug
    cocos2dx for iOS fmod的音效引擎接入
    skynet 学习笔记-sproto模块(2)
    cocos2dx for android 接入 fmod的过程
    skynet 学习笔记-netpack模块(1)
    linux 安装并且设置环境lua环境变量
  • 原文地址:https://www.cnblogs.com/lhgohead/p/6139673.html
Copyright © 2011-2022 走看看