更新时间:2023-01-31 14:40:43
Date
对象在内部表示UTC的时间,并且只能使用其运行时所在计算机的时区.投射.
The Date
object represents the time in UTC internally, and can only use the time zone of the machine its running on when projected.
绝对没有办法产生使用任意时区的Date
对象.您可能遇到的任何尝试操纵Date
对象的示例(例如通过添加或减去时区偏移量)都存在根本缺陷.
There's absolutely no way to produce a Date
object that uses an arbitrary time zone. Any examples you may come across that try to manipulate the Date
object (such by adding or subtracting time zone offsets) are fundamentally flawed.
Moment本身具有强大的时区支持,包括用于使用命名时区(而不只是时区偏移量)的moment-timezone扩展.但是,一旦返回到Date
对象-您就会回到该对象的行为的摆布状态.
Moment itself has great time zone support, including the moment-timezone extension for working with named time zones instead of just time zone offsets. But once you go back to a Date
object - you're back at the mercy of the behavior of that object.
对不起,但是无法实现您的要求.也许您可以详细说明为什么要这样做,我可以建议一种解决方法.
Sorry, but there's no way to achieve what you are asking. Perhaps you could elaborate as to why you wanted to do this, and I could recommend a workaround.
更新:关于您的更新,通常存在一种机制,用于从日期选择器中获取作为 text 而不是作为日期对象的值.在jQuery UI日期选择器控件的示例中,onSelect
事件已将其作为文本提供给您,或者您可以简单地调用.val()
而不是.datepicker('getDate')
来使文本脱离字段.一旦有了文本值,就可以随心所欲地对其进行解析.
Update: With regards to your update, usually there is a mechanism for getting the value from a date picker as text, rather than as a date object. With the example of the jQuery UI date picker control, the onSelect
event gives it to you as text already, or you can simply call .val()
instead of .datepicker('getDate')
to get the text out of the field. Once you have a textual value, you can then parse it with moment however you like.
类似地,在设置值时,您不一定需要Date
对象.您可以将文本框的值设置为字符串,也可以将字符串传递给 setDate
函数.
Similarly, when setting the value, you don't necessarily need a Date
object. You could just set the value of the textbox as a string, or you can pass a string to the setDate
function.
在大多数情况下,您不必遍历Date
对象.但是,如果您出于某种原因这样做,那么您将需要人为地构建一个疯狂的东西,例如:
In most cases, you won't have to go through a Date
object. But if for some reason you do, then you'll need to artificially construct one with something crazy like:
var d = new Date(m.format('YYYY/MM/DD'));
通常,我反对这样做-但是,如果只是为了将值传递给UI控件而已,那可能就可以了.
Normally, I'd be against that - but if it's just there to get the pass a value to a UI control, then it's probably ok.