我有一个MUI日期选择器,我可以选择一天没有时间。
示例:我选择
01.09.1970
在控制台中,日志为Tue Sep 01 1970 00:00:00 GMT+0100 (Mitteleuropäische Normalzeit)
这意味着我坐在时区UTC+1并选择午夜。但UTC+0早了一个小时(这就是问题所在)。
我已经有办法解决我的问题了:
const clonedBirthDate = new Date(birthDate.getTime());
clonedBirthDate.setUTCMinutes(- clonedBirthDate.getTimezoneOffset())
之后,clonedBirthDate的时间为
Tue Sep 01 1970 01:00:00 GMT+0100 (Mitteleuropäische Normalzeit)
UTC+0是在午夜。
我可以把它发送到一个ASP.NET API,对于世界上的每个用户,所选的日期是UTC+0的午夜。我需要在客户端进行,因为在ASP.NET中,我没有办法将它计算回用户的本地时间,因为我不知道后端用户的时区。
这段代码看起来像是一个解决方案。也许有一些更好的方法?
1条答案
按热度按时间icomxhvb1#
我们可以使用
Date/getFullYear
、Date/getMonth()
和Date/getDate()
方法获取年、月和日,然后将它们传递给Date.UTC()
方法,从而创建与UTC午夜相对应的Date。我们将输出(从1970-01-01 UTC开始的毫秒数)传递给Date构造函数,并得到utcMidnight,例如UTC中1970-09-01一天的开始。
您也可以将生日作为一个对象发送到后端,带有年、月、日属性,因为小时、分钟、秒等是不相关的。