当前位置:网站首页>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);
}
}边栏推荐
- TensorFlow custom training function
- Concepts of cloud-native applications and 15 characteristics of cloud-native applications
- Jingdong school recruited written test questions + summary of knowledge points
- 单片机工程师笔试题目归纳汇总
- Summary of text alignment, line height, space, etc.
- [Cloud-Building Co-creation] Huawei Cloud and Hongmeng collaborate to cultivate innovative developers
- 如何用Golang来手撸一个Blog - Milu.blog 开发总结
- UE5 GAS Study Notes Postscript 0
- [Database basics] redis usage summary
- TensorFlow自定义训练函数
猜你喜欢
随机推荐
云原生应用的概念和云原生应用的 15 个特征
TensorFlow custom training function
电压继电器HDY-A/1-220VAC-1
Based on sliding mode control of uncertain neutral system finite time stable
Concepts of cloud-native applications and 15 characteristics of cloud-native applications
原生js 创建表格
Matlab基础(3)——元胞与结构体
The package of idea is not hollow
获取1688app上原数据 API
Taobao/Tmall taobao comments q&a list interface API
模糊离散事件系统的可测性
SQL language and paging rownum analysis in Oracle
Leetcode 125. 验证回文串
idea的package没有空心
High energy output!Tencent's internal MyCat middleware manual, both theoretical and practical
2022-07-29 Gu Yujia Study Notes Exception Handling
VSCode更改插件的安装位置
Verilog语法基础HDL Bits训练 08
EA中的业务对象和业务实体你分得清吗?
Redis 主从复制








