C# Json 字符串时间 转对象

内容纲要

使用Json存储时间需要转为对象时,
要使用如下面的格式

2019-12-06T17:15:52Z

Z 表示时区
使用示例:
表示北京时间

2019-12-06T17:15:52+08:00

但是前端、C#时间转换和数据库的时间处理,协调起来会比较麻烦,JSON和字符串转时间也会麻烦。

根据笔者的校验,建议使用 UNIX 时间戳 形式传递。

C# 快速将当前时间转换为时间戳的代码为(以秒为单位)

(DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000 / 1000

如果你想以毫秒为单位

(DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000

C# 时间转换的常用代码

        /// <summary>
        /// 获取1970-01-01至dateTime的秒数,不带时区
        /// </summary>
        public static long GetTimestamp(DateTime dateTime)
        {
            DateTime dt1970 = new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return (dateTime.Ticks - dt1970.Ticks) / 10000 / 1000;
        }

        /// <summary>
        /// 根据时间戳timestamp(单位 秒)计算日期,不带时区
        /// </summary>
        public static DateTime NewDate(long timestamp)
        {
            DateTime dt1970 = new DateTime(1970, 1, 1, 0, 0, 0, 0);
            long t = dt1970.Ticks + timestamp * 10000 * 1000;
            return new DateTime(t);
        }

        /// <summary>
        /// 将字符串转为时间
        /// </summary>
        /// <param name="dateString"></param>
        /// <returns></returns>
        public static DateTime StringToDateTime(string dateString)
        {
            //格式必须为 2019-03-13 14:49:10.8327809
            DateTime dt = Convert.ToDateTime(dateString, System.Globalization.CultureInfo.CurrentCulture);
            return dt;
        }
点赞
  1. purchase remeron说道:

    My spouse and i felt now fulfilled that Ervin could deal with his investigations out of the ideas he got out of the web page. It's not at all simplistic to just choose to be giving freely instructions that many other folks have been selling. And we also figure out we have the website owner to be grateful to for that. The entire explanations you have made, the simple site menu, the friendships you can give support to engender - it's got everything fantastic, and it's really facilitating our son and the family feel that the issue is entertaining, and that is incredibly indispensable. Thank you for all the pieces!

  2. effexor buy说道:

    My husband and i felt absolutely excited Emmanuel could carry out his basic research by way of the ideas he came across from your own blog. It's not at all simplistic just to always be giving away guidelines many others could have been making money from. And now we consider we've got the blog owner to appreciate because of that. All the explanations you've made, the easy blog menu, the friendships you aid to create - it's all astounding, and it's aiding our son and our family consider that that concept is awesome, and that's exceptionally essential. Many thanks for all!

发表评论

邮箱地址不会被公开。 必填项已用*标注

You must enable javascript to see captcha here!