问题分析日期显示不正确的日期 [英] Issue Parsing Date Showing Incorrect Date

查看:84
本文介绍了问题分析日期显示不正确的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个生成今天日期的JS函数:

I have a JS function that generates today date:

function GetDate(date) {
    var today = new Date();
    var dd = String(today.getDate()).padStart(2, '0');
    var mm = String(today.getMonth() + 1).padStart(2, '0'); 
    var yyyy = today.getFullYear();

    today = dd + '/' + mm + '/' + yyyy;

    alert(today);

    return today;  // 13/03/2021
}

此函数返回 13/03/2021

我将其传递给服务器端代码,然后执行此操作:

I pass it on to Server Side Code and do this :

DateTime dateToday = DateTime.ParseExact(cdate, "dd/MM/yyyy", CultureInfo.GetCultureInfo("en-AU"));
emailCopy = emailCopy.Replace("{date}", dateToday.ToString("dd MMMM yyyy"));

但是在这里将日期设置为 2021年3月12日

However here it puts the date as 12 March 2021

为什么这样做?输入的日期显然是 13/03/2021 .同样在下一行中,我传递了要添加到SQL Server表中的日期:

Why is it doing that? The date going in is clearly 13/03/2021. Also in next line I pass this date to be added to SQL Server Table:

dateToday.ToString("yyyy-MM-dd")

添加到数据库中的日期也正确: 2021-03-13.

And the date added to the database is also correct : 2021-03-13.

推荐答案

创建新的 DateTime 对象时,仅设置了日期部分,将时间设置为00:00:00(午夜).这是格林尼治标准时间.因此,当您格式化日期时,它将采用您在午夜设置的日期,并将其转换为您所在的时区,实际上是前一天.

When you create a new DateTime object, but only set the date part of it, this sets the time to 00:00:00 (midnight). This is in GMT. So when you format the date it takes the date you set at midnight, and converts it to your time zone, which is actually the day before.

您可以通过执行"kludge"来解决此问题:

You can fix this by doing this "kludge":

var now = DateTime.Now;
var adjusted = new DateTime(
    dateToday.Year, dateToday.Month, dateToday.Day, now.Hour, now.Minute, now.Second);
var final = adjusted.ToString("dd MMMM yyyy");

不过,也许有更好的方法.

There may be a better way to do this, though.

ETA

您应该考虑使用JavaScript的 Date.toISOString(),而不只是发送日期.然后在C#中,使用 Convert.ToDateTime()对其进行解析.该代码使用UTC,可以确保您获得客户端计算机生成日期的确切时间.

You should consider using JavaScript's Date.toISOString() instead of just sending the date. Then in C#, use Convert.ToDateTime() to parse it. That uses UTC and you are guaranteed to get the exact time that the client machine generated the date.

这篇关于问题分析日期显示不正确的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆