C#中DateTime数据类型和16进制的数据转化

思路可以把DateTime和一个时间戳相减得到TimeSpan类型,然后转化成秒数得到byte数组 由数组转化成ToString(“X2”)
反之则反, 下面上代码:

using System;
using System.Collections.Generic;
using System.Text;

namespace Commom
{
   public  class DateTimeInterHex
    {
       /// <summary>
       /// 把一个时间转化成四个字节的16进制字符串
       /// </summary>
       /// <param name="time">要转化的时间</param>
       /// <returns></returns>
       public static String TimeToHex(DateTime time)
       {
           StringBuilder sb = new StringBuilder();
           DateTime timeStar = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime (1970,01,01));
           TimeSpan timeSpan= time - timeStar;
           uint unitSpan= Convert.ToUInt32(timeSpan.TotalSeconds);
           if (unitSpan<0)
           {
               return sb.ToString();
           }
           byte[] bytes = System.BitConverter.GetBytes(unitSpan);
           for (int i = bytes.Length-1; i >= 0; i--)
           {
               sb.Append(bytes[i].ToString("X2"));
           }
           return sb.ToString();
       }
       /// <summary>
       /// 把十六进制数据转化成时间
       /// </summary>
       /// <param name="HexStr">16进制数据字符串</param>
       /// <returns></returns>
       public static DateTime HexToTime(string HexStr)
       {
           HexStr = HexStr.Replace(" ", "");
           DateTime time = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970,01,01));
           if (HexStr.StartsWith("oX")||HexStr.StartsWith("OX"))
           {
               HexStr = HexStr.Substring(2, HexStr.Length - 2);
           }
         
           if (HexStr.Length%2!=0)
           {
               HexStr += " ";
           }
           byte[] bytes=new byte[HexStr.Length/2];
           for (int i = 0; i < bytes.Length; i++)
           {
               bytes[bytes.Length-1-i] = Convert.ToByte(HexStr.Substring(i * 2, 2), 16);
           }
           uint unitSpan = System.BitConverter.ToUInt32(bytes, 0);
           return time.AddSeconds(unitSpan);
       }
    }
}

测试文本 2009-12-19 13:55:11 转成 4B 2C 6A BF
   4B 2C CD 2F 转成 2009-12-19 20:55:11
2020/4/8 17:04:53转化成 5E8D93B5

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

望天hous

你的鼓励是我最大动力~谢谢啦!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值