当前位置:网站首页>C# 时间戳与时间的互相转换
C# 时间戳与时间的互相转换
2022-07-30 11:30:00 【※※冰馨※※】
什么是时间戳?
时间戳是指格林威治时间1970年01月01日00时00分00秒(北京时间1970年01月01日08时00分00秒)起至现在的总秒数。
时间戳在线转换网址:https://tool.lu/timestamp,时间戳的转换网址有很多,经常用的还有站长工具。
下附代码,在控制台中粘贴在启动类即可使用,需引用(using System)命名空间 ;
/// <summary>
/// 取时间戳,高并发情况下会有重复。想要解决这问题请使用sleep线程睡眠1毫秒。
/// </summary>
/// <param name="AccurateToMilliseconds">精确到毫秒</param>
/// <returns>返回一个长整数时间戳</returns>
public static long GetTimeStamp(bool AccurateToMilliseconds = false)
{
if (AccurateToMilliseconds)
{
// 使用当前时间计时周期数(636662920472315179)减去1970年01月01日计时周期数(621355968000000000)除去(删掉)后面4位计数(后四位计时单位小于毫秒,快到不要不要)再取整(去小数点)。
//备注:DateTime.Now.ToUniversalTime不能缩写成DateTime.Now.Ticks,会有好几个小时的误差。
//621355968000000000计算方法 long ticks = (new DateTime(1970, 1, 1, 8, 0, 0)).ToUniversalTime().Ticks;
return (DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000;
}
else
{
//上面是精确到毫秒,需要在最后除去(10000),这里只精确到秒,只要在10000后面加三个0即可(1秒等于1000毫米)。
return (DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000;
}
}
/// <summary>
/// 时间戳反转为时间,有很多中翻转方法,但是,请不要使用过字符串(string)进行操作,大家都知道字符串会很慢!
/// </summary>
/// <param name="TimeStamp">时间戳</param>
/// <param name="AccurateToMilliseconds">是否精确到毫秒</param>
/// <returns>返回一个日期时间</returns>
public static DateTime GetTime(long TimeStamp, bool AccurateToMilliseconds = false)
{
System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); // 当地时区
if (AccurateToMilliseconds)
{
return startTime.AddTicks(TimeStamp * 10000);
}
else
{
return startTime.AddTicks(TimeStamp * 10000000);
}
}边栏推荐
猜你喜欢

RY-D1/1电压继电器

又爆神作!阿里爆款MySQL高级宝典开源,直抵P7

限时招募!淘宝无货源副业,800/天,不限经验,男女皆可,仅限前200名!

Interviewer: Redis bloom filter and the cuckoo in the filter, how much do you know?

STM32F1读取MLX90632非接触式红外温度传感器

域名怎么注册备案解析?

win下怎么搭建php环境的方法教程

GBJ2510-ASEMI电机专用25A整流桥GBJ2510

24. 两两交换链表中的节点

Concepts of cloud-native applications and 15 characteristics of cloud-native applications
随机推荐
Underwater target detection method based on spatial feature selection
[Database basics] redis usage summary
Difference between C# enumeration type and xaml
MySQL——数据库基础
Matlab基础(5)——符号运算
Scheduling of combined electric-heating system based on multi-objective two-stage stochastic programming method
LCD1602 display experiment developed by single chip microcomputer
Differences between lock spin and mutex usage scenarios
Testability of Fuzzy Discrete Event Systems
基于时延估计的扰动卡尔曼滤波器外力估计
流水线上的农民:我在工厂种蔬菜
反转链表-迭代反转法
Reverse linked list - iterative inversion method
基于加权灰色关联投影的Bagging-Blending多模型融合短期电力负荷预测
SCM engineers written questions induction summary
Current relay JL-8GB/11/AC220V
High energy output!Tencent's internal MyCat middleware manual, both theoretical and practical
Apifox 生成接口文档 教程与操作步骤
Matlab基础(1)——基础知识
C language - bitwise operations