4.4. 将Javascript中的"new Date(xxx)"转换为C#中的DateTime变量:parseJsNewDate


//parse xxx in "new Date(xxx)" of javascript to C# DateTime
//input example:
//new Date(1329198041411.84) / new Date(1329440307389.9) / new Date(1329440307483)
public bool parseJsNewDate(string newDateStr, out DateTime parsedDatetime)
{
bool parseOK = false;
parsedDatetime = new DateTime();

if ((newDateStr != "") && (newDateStr.Trim() != ""))
{
    string dateValue = "";
    if (extractSingleStr(@".*new\sDate\((.+?)\).*", newDateStr, out dateValue))
    {
        double doubleVal = 0.0;
        if (Double.TryParse(dateValue, out doubleVal))
        {
            // try whether is double/int64 milliSecSinceEpoch
            parsedDatetime = milliSecToDateTime(doubleVal);
            parseOK = true;
        }
        else if (DateTime.TryParse(dateValue, out parsedDatetime))
        {
            // try normal DateTime string
            //refer: http://www.w3schools.com/js/js_obj_date.asp
            //October 13, 1975 11:13:00
            //79,5,24 / 79,5,24,11,33,0
            //1329198041411.3344 / 1329198041411.84 / 1329198041411
            parseOK = true;
        }
    }
}

return parseOK;
}

        

例 4.4. parseJsNewDate 的使用范例

DateTime expireTime;
if (parseJsNewDate(expire, out expireTime))
{
    parsedCk.Expires = expireTime;
}