that I find interesting
« Election cycle advertising, casinos, and trickle down economicsProcrastination »

Using culture-sensitive C# dates with Javascript

  12/23/11 12:25, by , Categories: Informative, Programming

I was trying to create a javascript date object using a C# date in my view like this:


var jsDate = new Date('<%=myDate.ToString("MM/dd/yyyy")%>');

It worked as expected when the culture was en-US, but not when the culture was fr-CA.

I figured out that C# was outputting the date with hyphens instead of slashes, even though I specified slashes in the format I passed to ToString().

Once I added quotes around the slashes, everything worked perfectly:


var jsDate = new Date('<%=myDate.ToString("MM'/'dd'/'yyyy")%>');


As per Jeff’s comment below, the following code also works:


var jsDate = new Date('<%=myDate.ToString("MM/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture)%>');

This entry was posted by and is filed under Informative, Programming.

1 comment

Comment from:
Jeff Cutsinger

I might be mistaken, but I think DateTime.ToString has an overload that allows you to pass in a culture. For cases like this it’s appropriate to pass in CultureInfo.InvariantCulture, since you aren’t displaying the output (at least not directly).

01/12/12 @ 17:21

Form is loading...

February 2020
Sun Mon Tue Wed Thu Fri Sat
 << <   > >>
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29


  XML Feeds


©2020 by Dustin Sullivan

Contact | Help | Blog theme by Asevo | blogging software | low cost web hosting