如何将JavaScript日期转换为UTC?
假设您网站的用户输入了日期范围如何将JavaScript日期转换为UTC?,javascript,date,utc,Javascript,Date,Utc,假设您网站的用户输入了日期范围 2009-1-1 to 2009-1-3 您需要将此日期发送到服务器进行某些处理,但服务器希望所有日期和时间都以UTC为单位 现在假设用户在阿拉斯加、夏威夷或斐济。由于它们位于与UTC完全不同的时区,因此需要将日期范围转换为如下内容: 2009-1-1T8:00:00 to 2009-1-4T7:59:59 使用JavaScript日期对象,如何将第一个“本地化”日期范围转换为服务器可以理解的内容?是否尝试将日期转换为类似的字符串 var myDate = n
2009-1-1 to 2009-1-3
您需要将此日期发送到服务器进行某些处理,但服务器希望所有日期和时间都以UTC为单位
现在假设用户在阿拉斯加、夏威夷或斐济。由于它们位于与UTC完全不同的时区,因此需要将日期范围转换为如下内容:
2009-1-1T8:00:00 to 2009-1-4T7:59:59
使用JavaScript日期对象,如何将第一个“本地化”日期范围转换为服务器可以理解的内容?是否尝试将日期转换为类似的字符串
var myDate = new Date(); // Set this to your date in whichever timezone.
var utcDate = myDate.toUTCString();
我会做一个函数来实现这一点,尽管有点争议,但还是将其添加到日期原型中。如果您不习惯这样做,那么可以将其作为一个独立函数,将日期作为参数传递
Date.prototype.getISOString = function() {
var zone = '', temp = -this.getTimezoneOffset() / 60 * 100;
if (temp >= 0) zone += "+";
zone += (Math.abs(temp) < 100 ? "00" : (Math.abs(temp) < 1000 ? "0" : "")) + temp;
// "2009-6-4T14:7:32+10:00"
return this.getFullYear() // 2009
+ "-"
+ (this.getMonth() + 1) // 6
+ "-"
+ this.getDate() // 4
+ "T"
+ this.getHours() // 14
+ ":"
+ this.getMinutes() // 7
+ ":"
+ this.getSeconds() // 32
+ zone.substr(0, 3) // +10
+ ":"
+ String(temp).substr(-2) // 00
;
};
Date.prototype.getISOString=function(){
var zone='',temp=-this.getTimezoneOffset()/60*100;
如果(温度>=0)区域+=“+”;
区域+=(数学绝对值(温度)<100?:(数学绝对值(温度)<1000?:)+温度;
//“2009-6-4T14:7:32+10:00”
返回此。getFullYear()//2009
+ "-"
+(this.getMonth()+1)//6
+ "-"
+this.getDate()//4
+“T”
+this.getHours()//14
+ ":"
+这是。getMinutes()//7
+ ":"
+this.getSeconds()//32
+分区substr(0,3)/+10
+ ":"
+字符串(临时).substr(-2)//00
;
};
如果您在UTC时间需要它,只需将所有get*函数替换为getUTC*,例如:getUTCFullYear、getUTCMonth、getUTCHours。。。然后在末尾添加“+00:00”,而不是用户的时区偏移量。Date.prototype.toUTCArray=function(){
Date.prototype.toUTCArray= function(){
var D= this;
return [D.getUTCFullYear(), D.getUTCMonth(), D.getUTCDate(), D.getUTCHours(),
D.getUTCMinutes(), D.getUTCSeconds()];
}
Date.prototype.toISO= function(){
var tem, A= this.toUTCArray(), i= 0;
A[1]+= 1;
while(i++<7){
tem= A[i];
if(tem<10) A[i]= '0'+tem;
}
return A.splice(0, 3).join('-')+'T'+A.join(':');
}
var D=这个;
返回[D.getUTCFullYear(),D.getUTCMonth(),D.getUTCDate(),D.getUTCHours(),
D.getUTCMinutes(),D.getUTCSeconds();
}
Date.prototype.toISO=函数(){
var tem,A=this.toUTCArray(),i=0;
A[1]+=1;
而(i++我刚刚发现Steven Levithan的1.2.3版本正是我想要的。它允许您为JavaScript日期提供格式字符串,并将从本地时间转换为UTC。下面是我现在使用的代码:
// JavaScript dates don't like hyphens!
var rectifiedDateText = dateText.replace(/-/g, "/");
var d = new Date(rectifiedDateText);
// Using a predefined mask from date.format.js.
var convertedDate = dateFormat(d, 'isoUtcDateTime');
我发现日期解析工作得最好。其他方法有跨浏览器问题,date.js之类的东西很久没有更新了
页面上也不需要日期选择器。您可以调用类似于文档中给出的示例的内容:
$.parseDate('yy-mm-dd', '2007-01-26');
愚笨
var date = new Date();
var now_utc = Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(),
date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());
return new Date(now_utc);
应该适用于大多数较新的浏览器。它在Firefox 6.0上返回2012-07-28T00:00:00.000Z
toISOString()
方法返回简化扩展ISO格式的字符串
格式(),长度始终为24或27个字符
(YYYY-MM-DDTHH:MM:ss.sssZ
或±yyyyy-MM-DDTHH:MM:ss.sssZ
),
时区始终为零UTC偏移量,如所示
后缀“Z
”
资料来源:
您需要的格式是使用.toISOString()
方法创建的。对于本机不支持此方法的旧浏览器(ie8及以下版本),可以找到垫片:
这将使您能够做您需要的事情:
var isoDateString=new Date().toISOString();
console.log(isoDateString);
以下是我的方法:
var now = new Date();
var utc = new Date(now.getTime() + now.getTimezoneOffset() * 60000);
生成的utc
对象实际上不是utc日期,而是一个本地日期,它被移动以匹配utc时间(请参见注释)。但是,实际上它可以完成这项工作。浏览器可能会有所不同,您还应该记住不要相信客户机生成的任何信息,也就是说,下面的语句对我很有用(Mac OS X 10.8.2上的谷歌Chrome v24)
var utcDate=new Date(new Date().getTime());
编辑:“这与仅新日期()
有何不同?”请参见此处:
- 如果未提供任何参数,则构造函数将根据系统设置为当前日期和时间创建一个JavaScript日期对象
- 注意:如果使用多个参数作为构造函数调用Date,则指定的参数表示本地时间。如果需要UTC,请使用具有相同参数的new Date()。(注意:Date.UTC()返回自1970-01-01 00:00 UTC以来的毫秒数)
按照前面的答案添加60000*Date.getTimezoneOffset()是不正确的。首先,您必须将所有日期/时间都视为UTC,并带有时区修饰符,以便于显示
同样,浏览器可能会有所不同,但是,Date.getTime()返回自1970-01-01 UTC/GMT以来的毫秒数。如果像我上面所做的那样使用此数字创建新日期,它将是UTC/GMT。但是,如果通过调用.toString()来显示它,它将显示在您的本地时区中,因为.toString()使用本地时区,而不是调用它的日期对象的时区
我还发现,如果在某个日期调用.getTimezoneOffset(),它将返回您的本地时区,而不是您调用它的日期对象的时区(但是,我无法验证这是否是标准的)
在我的浏览器中,添加60000*Date.getTimezoneOffset()会创建一个不是UTC的日期时间。但是,当在我的浏览器中显示时(例如:.toString()),它会在我的本地时区中显示一个日期时间,如果忽略时区信息,该日期时间将是正确的UTC时间。这个函数对我来说非常有用
function ParseDateForSave(dateValue) {
// create a new date object
var newDate = new Date(parseInt(dateValue.substr(6)));
// return the UTC version of the date
return newDate.toISOString();
}
在不更改日期/时间的情况下转换为ISO
var now = new Date(); // Fri Feb 20 2015 19:29:31 GMT+0530 (India Standard Time)
var isoDate = new Date(now.getTime() - now.getTimezoneOffset() * 60000).toISOString();
//OUTPUT : 2015-02-20T19:29:31.238Z
日期/时间发生变化时转换为ISO(日期/时间将发生变化)
处理日期时,我的建议是将日期从用户输入解析为单个字段。您可以将其用作完整字符串,但这是在玩火
JavaScript可以以不同的格式处理两个相同的日期
永远不要做以下事情:
new Date('date as text');
将日期从用户输入解析为各个字段后,创建一个日期对象。
isoDate = new Date(now).toISOString();
//OUTPUT : 2015-02-20T13:59:31.238Z
new Date('date as text');
var year = getFullYear('date as text');
var month = getMonth('date as text');
var dayOfMonth = getDate('date as text');
var date = new Date(year, month, dayOfMonth);
var offsetInMs = ((date.getTimezoneOffset() * 60) // Seconds
* 1000); // Milliseconds
var utcDate = new Date(date.getTime + offsetInMs);
moment(yourTime).utc()
moment(yourTime).utc().format("YYYY-MM-DD")
moment.tz(yourUTCTime, "America/New_York")
var userdate = new Date("2009-1-1T8:00:00Z");
var timezone = userdate.getTimezoneOffset();
var serverdate = new Date(userdate.setMinutes(userdate.getMinutes()+parseInt(timezone)));
var utcDateString = new Date(new Date().toUTCString()).toISOString();
function getLocalIsoDateTime(dtString) {
if(dtString == "")
return "";
var offset = new Date().getTimezoneOffset();
var localISOTime = (new Date(new Date(dtString) - offset * 60000 /*offset in milliseconds*/)).toISOString().slice(0,-1);
//Next two lines can be removed if zone isn't needed.
var absO = Math.abs(offset);
var zone = (offset < 0 ? "+" : "-") + ("00" + Math.floor(absO / 60)).slice(-2) + ":" + ("00" + (absO % 60)).slice(-2);
return localISOTime + zone;
}
const moment = require('moment');
const utc = moment.utc(new Date(string));
new Date('2019-03-11')
Sun Mar 10 2019 18:00:00 GMT-0600 (Central Standard Time)
new Date('2019-03-11 ' + new Date().getHours() + ':' + new Date().getMinutes())
Mon Mar 11 2019 04:36:00 GMT-0600 (Central Standard Time)
const moment = require('moment');
let b = new Date(moment.utc('2014-02-20 00:00:00.000000'));
let utc = b.toUTCString();
b.getTime();
//First i had a string called stringDateVar that i needed to convert to Date
var newDate = new Date(stringDateVar)
//output: 2019-01-07T04:00:00.000Z
//I needed it 2019-01-07T00:00:00.000Z because i had other logic that was dependent on that
var correctDate = new Date(newDate.setUTCHours(0))
//This will output 2019-01-07T00:00:00.000Z on everything which allows scalability
export function convertLocalDateToUTCIgnoringTimezone(date: Date) {
const timestamp = Date.UTC(
date.getFullYear(),
date.getMonth(),
date.getDate(),
date.getHours(),
date.getMinutes(),
date.getSeconds(),
date.getMilliseconds(),
);
return new Date(timestamp);
}
export function convertUTCToLocalDateIgnoringTimezone(utcDate: Date) {
return new Date(
utcDate.getUTCFullYear(),
utcDate.getUTCMonth(),
utcDate.getUTCDate(),
utcDate.getUTCHours(),
utcDate.getUTCMinutes(),
utcDate.getUTCSeconds(),
utcDate.getUTCMilliseconds(),
);
}
function saveTaskDate(localDate: Date) {
// I convert your local calendar date so it looks like you've picked it being in UTC somewhere around London
const utcDate = convertLocalDateToUTCIgnoringTimezone(localDate);
api.saveTaskDate(utcDate);
}
function readTaskDate(taskUtcDate: Date) {
// I convert this UTC date to 'look in your local timezone' as if you were now in UTC somewhere around london
const localDateWithSameDayAsUTC = convertUTCToLocalDateIgnoringTimezone(taskUtcDate);
// this date will have the same calendar day as the one you've picked previously
// no matter where you were saving it and where you are now
}
let date = new Date(YOUR_DATE).toISOString()
// It would give the date in format "2020-06-16T12:30:00.000Z" where Part before T is date in YYYY-MM-DD format, part after T is time in format HH:MM:SS and Z stands for UTC - Zero hour offset
let dtLocal = new Date()
let dt = new Date(dtLocal.toISOString().split('Z')[0])
const now = new Date();
const year = now.getUTCFullYear();
const month = now.getUTCMonth();
const day = now.getUTCDate();
const hour = now.getUTCHours();
const tomorrowUTC= new Date();
tomorrowUTC.setDate(day + 1); // +1 because my logic is to get "tomorrow"
tomorrowUTC.setYear(year);
tomorrowUTC.setMonth(month);
tomorrowUTC.Hours(hour);
// then use the tomorrowUTC for to display/format it
// tomorrowUTC is a "Date" and not a string.