关键词

js时间戳和c#时间戳互转方法(推荐)

下面为您详细讲解“js时间戳和c#时间戳互转方法(推荐)”的完整攻略。

背景介绍

在前端开发和后端开发的交互过程中,可能会涉及到时间的转换,例如前端的js时间戳和后端的c#时间戳。在这种情况下,需要掌握js时间戳和c#时间戳的互转方法。

js时间戳和c#时间戳的定义

  • js时间戳:指距离1970年1月1日00:00:00的毫秒数。可以使用 Date.now() 函数获取当前时间的js时间戳。
  • c#时间戳:指距离1970年1月1日00:00:00的秒数。可以使用 .NET框架下的 DateTime.Now.ToUnixTimeSeconds() 函数获取当前时间的c#时间戳。

js时间戳转换为c#时间戳的方法

function jsTimestampToCSharpTimestamp(jsTimestamp){
  var cSharpTimestamp = jsTimestamp / 1000; // js时间戳是毫秒数,需要转换成秒数
  return cSharpTimestamp;
}

c#时间戳转换为js时间戳的方法

DateTime startTime = TimeZoneInfo.ConvertTime(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc), TimeZoneInfo.Utc);
TimeSpan timeSpan = DateTime.UtcNow - startTime;
long cSharpTimestamp = (long)timeSpan.TotalSeconds;

示例说明

示例1

假设当前时间为2021-06-01 12:00:00,使用js获取当前时间的js时间戳为1622534400000。将该js时间戳转换为c#时间戳的方法如下:

var jsTimestamp = 1622534400000;
var cSharpTimestamp = jsTimestampToCSharpTimestamp(jsTimestamp);
console.log(cSharpTimestamp); // 输出为:1622534400

示例2

假设后端返回的某个时间为2021-06-01 12:00:00的c#时间戳为1622534400。将该c#时间戳转换为js时间戳的方法如下:

DateTime startTime = TimeZoneInfo.ConvertTime(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc), TimeZoneInfo.Utc);
DateTime cSharpTime = startTime.AddSeconds(1622534400);
long jsTimestamp = (long)(cSharpTime - startTime).TotalMilliseconds;
Console.WriteLine(jsTimestamp); // 输出为:1622534400000

以上就是js时间戳和c#时间戳互转的方法。

本文链接:http://task.lmcjl.com/news/9954.html

展开阅读全文