转换C#日期时间为Javascript日期 [英] Convert C# DateTime to Javascript Date
问题描述
我在Javascript从MVC收到一个C#日期时间的函数。
如果日期为null,则它应该返回 - ,如果它是一个有效的日期就应该返回格式化日期
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.
重要提示:这是不可能送该日期从C#另一种格式
IMPORTANT: It's not possible to send the date in another format from C#.
使用Javascript:
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();
}
有没有更好的方式来比较,如果日期是C#新的datetime?
Is there a better way to compare if the date is the C# New DateTime?
和我怎么分析,并在YYYY / MM / DD格式?
And how do I parse and return the date in "yyyy/MM/dd" format?
推荐答案
由于你坚持的输出,我想不出什么更好的方式来在JavaScript端抓到的的DateTime
0
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
应努力为您解析的需求,但它返回的毫秒数,所以你需要环绕它Date构造函数:
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
和 date.getDate
0被索引,而不是1索引)
(date.getMonth
and date.getDate
are 0-indexed instead of 1-indexed.)
小提琴:的http://jsfiddle.net/GyC3t/ 行使>
Fiddle: http://jsfiddle.net/GyC3t/
修改
由于JoeB的渔获量,让我做了修正。在 date.getMonth()
函数0索引,但 date.getDate()
函数1索引。小提琴是工作与+1因为date.getMonth工作在当地的时间,这是UTC前。我没有正确检查文档,并且只是增加1,并将其与小提琴合作
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:
有关归期,你只是想
date.getFullYear() + "/" + (date.getMonth() + 1) + "/" + (date.getUTCDate());
( date.getMonth
为0索引。而 date.getDate
为1索引,但容易受时区差异)
(date.getMonth
is 0-indexed while date.getDate
is 1-indexed but susceptible to time-zone differences.)
小提琴:的 http://jsfiddle.net/GyC3t/25/
这篇关于转换C#日期时间为Javascript日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!