在工作过程中遇到时间格式的数据在C#、js 和 json保存的不同结果,现在总结一下
JavaScript Parser:
1、数字型时间转字符串时间
如var data = "/Date(1387533960820)/";
result = StrDateTo(result);
Console.Write(result);
输出:2013-12-20 09:21
code:
var data = "/Date(1387533960820)/";
var result = IntDateTo(data);
function IntDateTo(data) {
var date = new Date(parseInt(data.replace("/Date(", "").replace(")/", ""), 10));
var result = date.getFullYear() + "-" + (date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1) + "-" + (date.getDate() < 10 ? "0" + date.getDate() : date.getDate()) + " " + (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":" + (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes());
return result;
}
var obj = eval('(' + '{Date:"2010-07-12T03:05:21Z"}' + ')');
alert(obj);
scanDate(obj, isoDateParser);
var dateValue = obj["Date"];
alert(dateValue);
function scanDate(obj, dateParser) {
for (var key in obj) {
obj[key] = dateParser(key, obj[key]);
if (typeof (obj[key]) === 'object') {
scanDate(obj[key], dateParser);
}
}
}
function isoDateParser(key, value) {
if (typeof value === 'string') {
var a = (/ ^ \ d {4} - \ d { 2} - \e{2} \e{2}:\e{2}:\e{2} $ /).exec(value);
var a = (/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)?$/).exec(value);
if (a) {
var utcMilliseconds = Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6]);
return new Date(utcMilliseconds);
}
}
return value;
}
C# Parser:
long time = MilliTimeStamp(DateTime.Now);
DateTime Time = ConvertTime(time);
console.write(time )
结果为:1387547586984
console.write(Time)
结果为一个DateTime时间对象:{2013-12-20 13:53:06}
public long MilliTimeStamp(DateTime TheDate)
{//转为数字型时间
DateTime d1 = new DateTime(1970, 1, 1).ToUniversalTime();
DateTime d2 = TheDate.ToUniversalTime();
TimeSpan ts = new TimeSpan(d2.Ticks - d1.Ticks);
return (long)ts.TotalMilliseconds;
}
public DateTime ConvertTime(long milliTime)
{//转为时间对象
long timeTricks = new DateTime(1970, 1, 1).Ticks + milliTime * 10000;
return new DateTime(timeTricks);
}
资料来源于博客园
1、http://www.cnblogs.com/dragonstreak_1/archive/2011/09/04/2165942.html