千家信息网

C#中unix与windows时间格式互转

发表于:2024-10-06 作者:千家信息网编辑
千家信息网最后更新 2024年10月06日,最近做shopEX平台订单对接,因为shopEX是Php的,所以在提交订单的时间格式首先转换成unix时间格式,然后才能提交成功。相同的,有response返回的所有的日期格式都是unix时间格式,所
千家信息网最后更新 2024年10月06日C#中unix与windows时间格式互转最近做shopEX平台订单对接,因为shopEX是Php的,所以在提交订单的时间格式首先转换成unix时间格式,然后才能提交成功。
相同的,有response返回的所有的日期格式都是unix时间格式,所以要转换成系统时间我们才能使用。
在网上搜了一下,整理了一下,下面是我用C#编写的小例子,供各位参考。数据的严谨性,需要在实际使用时进行相应的判断操作。
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
namespace ConsoleApplication1
{
///
/// unix与windowns日期格式互换
/// zhangyong 2012/03/07
///

class Program
{
private static readonly string time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
static void Main(string[] args)
{
string DataStr = time;
Program p = new Program();
string tempTime = p.ConvertToUnix(DataStr);
string ssd = p.ConvertToWin(tempTime);
}

///
/// 将nuix中的日期格式转换成正常日期格式,前提传入的格式正确
///

/// 传入的时间戳
///
public String ConvertToWin(String timestampString)
{
DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970,1,1));
long lTime = long.Parse(timestampString + "0000000");
TimeSpan toNow = new TimeSpan(lTime);
DateTime dtResult = dtStart.Add(toNow);
return dtResult.ToString("yyyy-MM-dd HH:mm:ss");
}
///
/// 将正常的日期转换成unix日期时间戳格式
///

/// 正常日期转换成的字符串格式如:yyyy-MM-dd HH:mm:ss
/// unix时间
public string ConvertToUnix(string dateTime)
{
DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
DateTime dtNow = DateTime.Parse(dateTime);
TimeSpan toNow = dtNow.Subtract(dtStart);
string timeStamp = toNow.Ticks.ToString();
timeStamp = timeStamp.Substring(0, timeStamp.Length - 7);
return timeStamp; }

}
}
0