你如何保存从浏览器到服务器的 JavaScript 日期的时区,然后返回?

2023-06-14前端开发问题
5

本文介绍了你如何保存从浏览器到服务器的 JavaScript 日期的时区,然后返回?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

例如,使用日期和时间控件,用户选择日期和时间,使得字符串表示如下:

For example, using a date and time control, the user selects a date and time, such that the string representation is the following:

"6-25-2012 12:00:00 PM"

这个用户恰好在 EST 时区.该字符串被传递到服务器,服务器将其转换为 .NET DateTime 对象,然后将其存储在 SQL Server 中的 datetime 列中.

It so happens that this user is in the EST time zone. The string is passed to the server, which translates it into a .NET DateTime object, and then stores it in SQL Server in a datetime column.

当稍后将日期返回给浏览器时,需要将其转换回日期,但是当将上述字符串输入日期时,它会损失 4 小时的时间.我相信这是因为在创建 JavaScript 日期时未指定时区时,它默认为本地时间,并且由于 EST 是格林威治标准时间的 -400,它会从下午 12 点减去 4 小时,即使下午 12 点本应指定为 EST 时用户在 EST 时区的机器上选择了它.

When the date is returned later to the browser, it needs to be converted back into a date, however when the above string is fed into a date it is losing 4 hours of time. I believe this is because when not specifying a timezone while creating a JavaScript date, it defaults to local time, and since EST is -400 from GMT, it subtracts 4 hours from 12pm, even though that 12pm was meant to be specified as EST when the user selected it on a machine in the EST time zone.

显然需要在原始日期时间字符串中添加一些内容,然后才能将其传递给服务器以进行持久化.这样做的推荐方法是什么?

Clearly something needs to be added to the original datetime string before its passed to the server to be persisted. What is the recommended way of doing this?

推荐答案

不要依赖 JavaScript 的 Date 构造函数来解析字符串.行为和支持的格式因浏览器和语言环境而异.如果您使用 Date一些 的默认行为> 直接对象.

Don't rely on JavaScript's Date constructor to parse a string. The behavior and supported formats vary wildly per browser and locale. Here are just some of the default behaviors if you use the Date object directly.

如果您必须来自字符串,请尝试使用标准化格式,例如 ISO8601.您以该格式提供的日期将是 "2012-06-25T12:00:00".在 JavaScript 中使用这些最简单的方法是使用 moment.js.

If you must come from a string, try using a standardized format such as ISO8601. The date you gave in that format would be "2012-06-25T12:00:00". The easiest way to work with these in JavaScript is with moment.js.

另外,请注意您实际要表达的意思.现在,您正在传递本地日期/时间,保存本地/日期/时间,并返回本地日期/时间.在此过程中,本地"的概念可能会发生变化.

Also, be careful about what you are actually meaning to represent. Right now, you are passing a local date/time, saving a local/date/time, and returning a local date/time. Along the way, the idea of what is "local" could change.

在许多情况下,日期/时间旨在表示准确时刻.为此,您需要在客户端将输入的本地时间转换为 UTC.将 UTC 发送到您的服务器并存储它.稍后,检索 UTC 并将其发送回您的客户端,将其作为 UTC 处理并转换回本地时间.您可以使用 moment.js 轻松完成所有这些工作:

In many cases, the date/time is intended to represent an exact moment in time. To make that work, you need to convert from the local time entered to UTC on the client. Send UTC to your server, and store it. Later, retrieve UTC and send it back to your client, process it as UTC and convert back to local time. You can do all of this easily with moment.js:

// I'll assume these are the inputs you have.  Adjust accordingly.
var dateString = "6-25-2012";
var timeString = "12:00:00 PM";

// Construct a moment in the default local time zone, using a specific format.
var m = moment(dateString + " " + timeString, "M-D-YYYY h:mm:ss A");

// Get the value in UTC as an ISO8601 formatted string
var utc = m.toISOString(); // output: "2012-06-25T19:00:00.000Z"

在.Net的服务器上:

On the server in .Net:

var dt = DateTime.Parse("2012-06-25T19:00:00.000Z",   // from the input variable
                        CultureInfo.InvariantCulture, // recommended for ISO
                        DateTimeStyles.RoundtripKind) // honor the Z for UTC kind

将其存储在数据库中.稍后取回并发送回去:

Store that in the database. Later retrieve it and send it back:

// when you pull it from your database, set it to UTC kind
var dt = DateTime.SpecifyKind((DateTime)reader["yourfield"], DateTimeKind.Utc);

// send it back in ISO format:
var s = dt.ToString("o"); // "o" is the ISO8601 "round-trip" pattern.

将它传回moment.js中的javascript:

Pass it back to the javascript in moment.js:

// construct a moment:
var m = moment("2012-06-25T19:00:00.000Z"); // use the value from the server

// display it in this user's local time zone, in whatever format you want
var s = m.format("LLL");   // "June 25 2012 12:00 PM"

// or if you need a Date object
var dt = m.toDate();

看 - 这很容易,而且您无需对时区进行任何花哨的操作.

See - that was easy, and you didn't need to get into anything fancy with time zones.

这篇关于你如何保存从浏览器到服务器的 JavaScript 日期的时区,然后返回?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

js删除数组中指定元素的5种方法
在JavaScript中,我们有多种方法可以删除数组中的指定元素。以下给出了5种常见的方法并提供了相应的代码示例: 1.使用splice()方法: let array = [0, 1, 2, 3, 4, 5];let index = array.indexOf(2);if (index -1) { array.splice(index, 1);}// array = [0,...
2024-11-22 前端开发问题
182

layui laydate日期时间范围,时间默认设定为23:59:59
在Layui中,如果你想设置日期时间选择器(datetime)的默认结束时间为当天的23:59:59,你可以使用如下代码: laydate.render({ elem: '#test10' ,type: 'datetime' ,range: true ,max: '{:date("Y-m-d 23:59:59")}' ,ready: function(date){ $(".layui-laydat...
2024-10-24 前端开发问题
279

JavaScript小数运算出现多位的解决办法
在开发JS过程中,会经常遇到两个小数相运算的情况,但是运算结果却与预期不同,调试一下发现计算结果竟然有那么长一串尾巴。如下图所示: 产生原因: JavaScript对小数运算会先转成二进制,运算完毕再转回十进制,过程中会有丢失,不过不是所有的小数间运算会...
2024-10-18 前端开发问题
301

JavaScript(js)文件字符串中丢失"\"斜线的解决方法
问题描述: 在javascript中引用js代码,然后导致反斜杠丢失,发现字符串中的所有\信息丢失。比如在js中引用input type=text onkeyup=value=value.replace(/[^\d]/g,) ,结果导致正则表达式中的\丢失。 问题原因: 该字符串含有\,javascript对字符串进行了转...
2024-10-17 前端开发问题
437

layui中table列表 增加属性 edit="date",不生效怎么办?
如果你想在 layui 的 table 列表中增加 edit=date 属性但不生效,可能是以下问题导致的: 1. 缺少日期组件的初始化 如果想在表格中使用日期组件,需要在页面中引入 layui 的日期组件,并初始化: script type="text/javascript" src="/layui/layui.js"/scrip...
2024-06-11 前端开发问题
455

Rails/Javascript:如何将 rails 变量注入(非常)简单的 javascript
Rails/Javascript: How to inject rails variables into (very) simple javascript(Rails/Javascript:如何将 rails 变量注入(非常)简单的 javascript)...
2024-04-20 前端开发问题
5