Posted by Joe | Posted in ASP.NET, Ajax, JavaScript | Posted on 29-06-2010
JSON doesn’t have a standard way to represent a date. You can read about the reasons behind this here.
If you are using an ASMX web service returning JSON then you’ll find it serializes the DateTime object to a string that looks like this:
/Date(1278943200000)/
The numer in this string is the number of milliseconds since January 1st 1970 UTC, and this number can be used as a constructor argument to the JavaScript Date object. So all we need to do is extract the number of milliseconds from the string. This can be done easily using the regular expression shown in the post linked above.
var dateString = "/Date(1278943200000)/";
var date = new Date(parseInt(dateString.replace(/\/Date\((\d+)\)\//, '$1')));
In the above example I’ve manually set the date string, but you may get this from an AJAX response from the ASMX web service. I then create a new Date object by using the regular expression and parsing the result at an integer.

Posted by Joe | Posted in C# | Posted on 25-06-2010
Here’s a quick an easy way to show the time difference between two DateTime objects using C#.
The DateTime structure has an overridden subtract operator which return a TimeSpan object when subtracting two DateTimes:
public static TimeSpan operator -(DateTime d1, DateTime d2);
You can then use this TimeSpan to get the amount of time between each DateTime:
DateTime fromDate = DateTime.Now.AddDays(-1).AddMinutes(-10).AddSeconds(-20);
DateTime toDate = DateTime.Now;
TimeSpan timeSpan = toDate - fromDate;
string timeString =
string.Format(
"{0:00}:{1:00}:{2:00}",
(timeSpan.Days * 24) + timeSpan.Hours,
timeSpan.Minutes,
timeSpan.Seconds
);
In the above example I’m comparing a date in the past to the current date. This could be useful for working out the total amount of time that has passed since something has happened.
I’m then using the Hours, Minutes and Seconds properties of the TimeSpan to format a string displaying the amount of time. If the hours goes over 24 then the Days property is used, so for my hours I’m also adding on the number of days multiplied by 24.

Posted by Joe | Posted in C#, Linq | Posted on 10-06-2010