开发者

How to convert javascript numeric date into C# date (using C#, not javascript!)

I'm scraping a website and in the html it has a date in the following format:

"date"开发者_JAVA百科:"\/Date(1184050800000-0700)\/"

If this was in javascript, it would be a date object and I could use its methods to retrieve the data in whatever format I like. However, I'm scraping it in a C# app. Does anyone know what this format is? Is it the total number of seconds after a certain date or something? I need a way to convert this to a C# datetime object.


If I'm not mistaken, that is a Unix timestamp in milliseconds. 1184050800000 is the timestamp itself, and -0700 is the time zone. This epoch convertor confirms.

Here is some code I've used before for converting Unix timestamps into DateTimes. Be sure to include only the part before -0700:

/// <summary>
/// Converts a Unix timestamp into a System.DateTime
/// </summary>
/// <param name="timestamp">The Unix timestamp in milliseconds to convert, as a double</param>
/// <returns>DateTime obtained through conversion</returns>
public static DateTime ConvertFromUnixTimestamp(double timestamp)
{
    DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);
    return origin.AddSeconds(timestamp / 1000); // convert from milliseconds to seconds
}

If you encounter Unix timestamps that are in seconds, you just have to remove the / 1000 part of the last line of the code.


As sinelaw says it seems to be a regex of some sort, however I tried parsing out the numeric values:

1184050800000-0700

And they seem to correspond to:

  • 1184050800000 - Unix timestamp in milliseconds

  • -0700 - this would be the timezone offset UTC-07:00

You could parse it (I assume it's a string from a JSON object) and convert it to a DateTime like this:

string dateString = "/Date(1184050800000-0700)/";
Regex re = new Regex(@"(\d+)([-+]\d{4})");
Match match = re.Match(dateString);

long timestamp = Convert.ToInt64(match.Groups[1].Value);
int offset = Convert.ToInt32(match.Groups[2].Value) / 100;

DateTime date = new DateTime(1970, 1, 1).AddMilliseconds(timestamp).AddHours(-offset);
Console.WriteLine(date); // 7/10/2007 2:00:00 PM


Am I wrong? It looks like a regexp to me, not a date object at all.


DateTime now = new DateTime(1184050800000);
Console.WriteLine(now); // 2/01/0001 8:53:25 AM

Could this be correct if you aren't interested in the year?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜