Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert C# DateTime to Javascript Date

I have a function in Javascript that receives a C# DateTime from MVC. If the date is null it should return "-", if it's a valid date it should return the formated date.

IMPORTANT: It's not possible to send the date in another format from C#.

Javascript:

function CheckDate(date) {    if (date == "Mon Jan 01 0001 00:00:00 GMT+0000 (GMT Daylight Time)")     return "-";   else {     var dat = new Date(date);     return dat.getFullYear() + dat.getMonth() + dat.getDay();   } 

Is there a better way to compare if the date is the C# New DateTime?

And how do I parse and return the date in "yyyy/MM/dd" format?

like image 296
DK ALT Avatar asked Jul 30 '13 14:07

DK ALT


People also ask

What is C equal to in Fahrenheit?

Convert celsius to fahrenheit 1 Celsius is equal to 33.8 Fahrenheit.

What does C mean in conversion?

Quick Celsius (°C) / Fahrenheit (°F) Conversion: °C.

How do you convert C to F step by step?

Conversion Formula It is easy to convert Celsius to Fahrenheit by following these two steps: Multiply your Celsius measurement by 1.8. Add 32 to the result.


2 Answers

Given the output you're stuck with, I can't think of any better way to catch a DateTime of 0 on the javascript side.

Date.parse should work for your parsing needs, but it returns number of milliseconds, so you need to wrap a Date constructor around it:

var date = new Date(Date.parse(myCSharpString)); 

For the return date, you simply want

date.getFullYear() + "/" + (date.getMonth() + 1) + "/" + (date.getDate() + 1); 

(date.getMonth and date.getDate are 0-indexed instead of 1-indexed.)

Fiddle: http://jsfiddle.net/GyC3t/

EDIT Thanks to JoeB's catch, let me do a correction. The date.getMonth() function is 0-indexed, but the date.getDate() function is 1-indexed. The fiddle was "working" with the +1 because date.getMonth works in local time, which is before UTC. I didn't properly check the docs, and just added 1, and it worked with the fiddle.

A more proper way to do this is:

For the return date, you simply want

date.getFullYear() + "/" + (date.getMonth() + 1) + "/" + (date.getUTCDate()); 

(date.getMonth is 0-indexed while date.getDate is 1-indexed but susceptible to time-zone differences.)

Fiddle: http://jsfiddle.net/GyC3t/25/

like image 123
Scott Mermelstein Avatar answered Sep 30 '22 07:09

Scott Mermelstein


I use the following to pass a Javascript Date into C#:

var now = new Date(); var date = (now.getTime() / 86400000) - (now.getTimezoneOffset() / 1440) + 25569; 

So if you get the number of milliseconds from C#, it should be something like this:

var csharpmilliseconds; var now = new Date(); var date = new Date((csharpmilliseconds + (now.getTimezoneOffset() / 1440) - 25569) * 86400000); 
like image 24
Nick Gotch Avatar answered Sep 30 '22 08:09

Nick Gotch