I have been fighting with this for a bit now. I’m trying to convert epoch to a date object. The epoch is sent to me in UTC. Whenever you pass new Date()
an epoch, it assumes it’s local epoch. I tried creating a UTC object, then using setTime()
to adjust it to the proper epoch, but the only method that seems useful is toUTCString()
and strings don’t help me. If I pass that string into a new date, it should notice that it’s UTC, but it doesn’t.
我已经和这个斗争了一会儿了。我想把历元转换成日期对象。时代是用UTC发给我的。无论何时您通过一个新的日期(),它都假定它是本地的历元。我尝试创建一个UTC对象,然后使用setTime()将其调整为合适的历元,但是看起来唯一有用的方法是toUTCString(),而string并不能帮助我。如果我将这个字符串传递到一个新的日期,它应该注意到它是UTC,但它不是。
new Date( new Date().toUTCString() ).toLocaleString()
My next attempt was to try to get the difference between local current epoch and UTC current epoch, but I wasn’t able to get that either.
我的下一个尝试是尝试去弄清楚本地当前时代和UTC当前时代的区别,但我也没能弄明白。
new Date( new Date().toUTCString() ).getTime() - new Date().getTime()
It’s only giving me very small differences, under 1000, which is in milliseconds.
它只给出很小的差异,小于1000,单位是毫秒。
Any suggestions?
有什么建议吗?
12 个解决方案
#1
343
I think I have a simpler solution -- set the initial date to the epoch and add UTC units. Say you have a UTC epoch var stored in seconds. How about 1234567890
. To convert that to a proper date in the local time zone:
我想我有一个更简单的解决方案——将初始日期设为历元并添加UTC单位。假设您有一个以秒为单位存储的UTC历元var。如何1234567890。将其转换为当地时区的适当日期:
var utcSeconds = 1234567890;
var d = new Date(0); // The 0 there is the key, which sets the date to the epoch
d.setUTCSeconds(utcSeconds);
d
is now a date (in my time zone) set to Fri Feb 13 2009 18:31:30 GMT-0500 (EST)
d现在是一个日期(在我的时区),设定在2009年2月13日星期五18:31:30 GMT-0500(美国东部时间)
#2
116
It's easy, new Date()
just takes milliseconds, e.g.
很简单,new Date()只需要毫秒。
new Date(1394104654000)
> Thu Mar 06 2014 06:17:34 GMT-0500 (EST)
#3
27
And just for the logs, I did this using Moment.js library, which I was using for formatting anyway.
对于log,我用了这个时间。js库,我用它来格式化。
moment.utc(1234567890000).local()
>Fri Feb 13 2009 19:01:30 GMT-0430 (VET)
#4
14
function ToLocalDate (inDate) {
var date = new Date();
date.setTime(inDate.valueOf() - 60000 * inDate.getTimezoneOffset());
return date;
}
#5
13
Epoch time is in seconds from Jan. 1, 1970. date.getTime()
returns milliseconds from Jan. 1, 1970, so.. if you have an epoch timestamp, convert it to a javascript timestamp by multiplying by 1000.
纪元时间从1970年1月1日开始。gettime()从1970年1月1日起返回毫秒,因此。如果您有一个epoch时间戳,请通过乘以1000将其转换为javascript时间戳。
function epochToJsDate(ts){
// ts = epoch timestamp
// returns date obj
return new Date(ts*1000);
}
function jsDateToEpoch(d){
// d = javascript date obj
// returns epoch timestamp
return (d.getTime()-d.getMilliseconds())/1000;
}
#6
3
Are you just asking to convert a UTC string to a "local" string? You could do:
您是否只是要求将UTC字符串转换为“local”字符串?你能做的:
var utc_string = '2011-09-05 20:05:15';
var local_string = (function(dtstr) {
var t0 = new Date(dtstr);
var t1 = Date.parse(t0.toUTCString().replace('GMT', ''));
var t2 = (2 * t0) - t1;
return new Date(t2).toString();
})(utc_string);
#7
1
EDIT
编辑
var utcDate = new Date(incomingUTCepoch);
var date = new Date();
date.setUTCDate(utcDate.getDate());
date.setUTCHours(utcDate.getHours());
date.setUTCMonth(utcDate.getMonth());
date.setUTCMinutes(utcDate.getMinutes());
date.setUTCSeconds(utcDate.getSeconds());
date.setUTCMilliseconds(utcDate.getMilliseconds());
EDIT fixed
编辑固定
#8
1
If you prefer to resolve timestamps and dates conversions from and to UTC and local time without libraries like moment.js, take a look at the option below.
如果您喜欢在没有像moment这样的库的情况下解析来自UTC和本地时间的时间戳和日期转换。js,看看下面的选项。
For applications that use UTC timestamps, you may need to show the date in the browser considering the local timezone and daylight savings when applicable. Editing a date that is in a different daylight savings time even though in the same timezone can be tricky.
对于使用UTC时间戳的应用程序,您可能需要在浏览器中显示日期,考虑到本地时区和适用时的夏令时。即使在相同的时区,编辑一个在不同的夏令时时间的日期也是很困难的。
The Number
and Date
extensions below allow you to show and get dates in the timezone of the timestamps. For example, lets say you are in Vancouver, if you are editing a date in July or in December, it can mean you are editing a date in PST or PDT.
下面的数字和日期扩展允许您在时间戳的时区中显示和获取日期。例如,假设您在温哥华,如果您正在编辑7月或12月的日期,它可能意味着您正在编辑PST或PDT中的日期。
I recommend you to check the Code Snippet down below to test this solution.
我建议您检查下面的代码片段来测试这个解决方案。
Conversions from milliseconds
转换从毫秒
Number.prototype.toLocalDate = function () {
var value = new Date(this);
value.setHours(value.getHours() + (value.getTimezoneOffset() / 60));
return value;
};
Number.prototype.toUTCDate = function () {
var value = new Date(this);
value.setHours(value.getHours() - (value.getTimezoneOffset() / 60));
return value;
};
Conversions from dates
从日期转换
Date.prototype.getUTCTime = function () {
return this.getTime() - (this.getTimezoneOffset() * 60000);
};
Usage
使用
// Adds the timezone and daylight savings if applicable
(1499670000000).toLocalDate();
// Eliminates the timezone and daylight savings if applicable
new Date(2017, 6, 10).getUTCTime();
See it for yourself
看到你自己
// Extending Number
Number.prototype.toLocalDate = function () {
var value = new Date(this);
value.setHours(value.getHours() + (value.getTimezoneOffset() / 60));
return value;
};
Number.prototype.toUTCDate = function () {
var value = new Date(this);
value.setHours(value.getHours() - (value.getTimezoneOffset() / 60));
return value;
};
// Extending Date
Date.prototype.getUTCTime = function () {
return this.getTime() - (this.getTimezoneOffset() * 60000);
};
// Getting the demo to work
document.getElementById('m-to-local-button').addEventListener('click', function () {
var displayElement = document.getElementById('m-to-local-display'),
value = document.getElementById('m-to-local').value,
milliseconds = parseInt(value);
if (typeof milliseconds === 'number')
displayElement.innerText = (milliseconds).toLocalDate().toISOString();
else
displayElement.innerText = 'Set a value';
}, false);
document.getElementById('m-to-utc-button').addEventListener('click', function () {
var displayElement = document.getElementById('m-to-utc-display'),
value = document.getElementById('m-to-utc').value,
milliseconds = parseInt(value);
if (typeof milliseconds === 'number')
displayElement.innerText = (milliseconds).toUTCDate().toISOString();
else
displayElement.innerText = 'Set a value';
}, false);
document.getElementById('date-to-utc-button').addEventListener('click', function () {
var displayElement = document.getElementById('date-to-utc-display'),
yearValue = document.getElementById('date-to-utc-year').value || '1970',
monthValue = document.getElementById('date-to-utc-month').value || '0',
dayValue = document.getElementById('date-to-utc-day').value || '1',
hourValue = document.getElementById('date-to-utc-hour').value || '0',
minuteValue = document.getElementById('date-to-utc-minute').value || '0',
secondValue = document.getElementById('date-to-utc-second').value || '0',
year = parseInt(yearValue),
month = parseInt(monthValue),
day = parseInt(dayValue),
hour = parseInt(hourValue),
minute = parseInt(minuteValue),
second = parseInt(secondValue);
displayElement.innerText = new Date(year, month, day, hour, minute, second).getUTCTime();
}, false);
<link href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.11/semantic.css" rel="stylesheet"/>
<div class="ui container">
<p></p>
<h3>Milliseconds to local date</h3>
<input id="m-to-local" placeholder="Timestamp" value="0" /> <button id="m-to-local-button">Convert</button>
<em id="m-to-local-display">Set a value</em>
<h3>Milliseconds to UTC date</h3>
<input id="m-to-utc" placeholder="Timestamp" value="0" /> <button id="m-to-utc-button">Convert</button>
<em id="m-to-utc-display">Set a value</em>
<h3>Date to milliseconds in UTC</h3>
<input id="date-to-utc-year" placeholder="Year" style="width: 4em;" />
<input id="date-to-utc-month" placeholder="Month" style="width: 4em;" />
<input id="date-to-utc-day" placeholder="Day" style="width: 4em;" />
<input id="date-to-utc-hour" placeholder="Hour" style="width: 4em;" />
<input id="date-to-utc-minute" placeholder="Minute" style="width: 4em;" />
<input id="date-to-utc-second" placeholder="Second" style="width: 4em;" />
<button id="date-to-utc-button">Convert</button>
<em id="date-to-utc-display">Set the values</em>
</div>
#9
1
To convert the current epoch time in [ms] to a 24-hour time. You might need to specify the option to disable 12-hour format.
将[ms]的当前纪元时间转换为24小时。您可能需要指定禁用12小时格式的选项。
$ node.exe -e "var date = new Date(Date.now()); console.log(date.toLocaleString('en-GB', { hour12:false } ));"
2/7/2018, 19:35:24
or as JS:
或者JS:
var date = new Date(Date.now());
console.log(date.toLocaleString('en-GB', { hour12:false } ));
// 2/7/2018, 19:35:24
console.log(date.toLocaleString('en-GB', { hour:'numeric', minute:'numeric', second:'numeric', hour12:false } ));
// 19:35:24
Note: The use of en-GB
here, is just a (random) choice of a place using the 24 hour format, it is not your timezone!
注意:en-GB在这里的使用,只是使用24小时格式的一个(随机的)选择,它不是您的时区!
#10
0
@Amjad, good idea, but implemented poorly. Try
@Amjad,是个好主意,但实施得很糟糕。试一试
Date.prototype.setUTCTime = function(UTCTimestamp) {
var UTCDate = new Date(UTCTimestamp);
this.setUTCFullYear(UTCDate.getFullYear(), UTCDate.getMonth(), UTCDate.getDate());
this.setUTCHours(UTCDate.getHours(), UTCDate.getMinutes(), UTCDate.getSeconds(), UTCDate.getMilliseconds());
return this.getTime();
}
#11
0
Considering, you have epoch_time
available,
考虑到,你有epoch_time可用,
// for eg. epoch_time = 1487086694.213
var date = new Date(epoch_time * 1000); // multiply by 1000 for milliseconds
var date_string = date.toLocaleString('en-GB'); // 24 hour format
#12
0
First convert it to String and then replace the timezone text.
首先将其转换为字符串,然后替换时区文本。
function convertUnixTime(time) {
return new Date(time*1000).toString().replace("GMT+0530 (Sri Lanka Standard Time)","");
}
#1
343
I think I have a simpler solution -- set the initial date to the epoch and add UTC units. Say you have a UTC epoch var stored in seconds. How about 1234567890
. To convert that to a proper date in the local time zone:
我想我有一个更简单的解决方案——将初始日期设为历元并添加UTC单位。假设您有一个以秒为单位存储的UTC历元var。如何1234567890。将其转换为当地时区的适当日期:
var utcSeconds = 1234567890;
var d = new Date(0); // The 0 there is the key, which sets the date to the epoch
d.setUTCSeconds(utcSeconds);
d
is now a date (in my time zone) set to Fri Feb 13 2009 18:31:30 GMT-0500 (EST)
d现在是一个日期(在我的时区),设定在2009年2月13日星期五18:31:30 GMT-0500(美国东部时间)
#2
116
It's easy, new Date()
just takes milliseconds, e.g.
很简单,new Date()只需要毫秒。
new Date(1394104654000)
> Thu Mar 06 2014 06:17:34 GMT-0500 (EST)
#3
27
And just for the logs, I did this using Moment.js library, which I was using for formatting anyway.
对于log,我用了这个时间。js库,我用它来格式化。
moment.utc(1234567890000).local()
>Fri Feb 13 2009 19:01:30 GMT-0430 (VET)
#4
14
function ToLocalDate (inDate) {
var date = new Date();
date.setTime(inDate.valueOf() - 60000 * inDate.getTimezoneOffset());
return date;
}
#5
13
Epoch time is in seconds from Jan. 1, 1970. date.getTime()
returns milliseconds from Jan. 1, 1970, so.. if you have an epoch timestamp, convert it to a javascript timestamp by multiplying by 1000.
纪元时间从1970年1月1日开始。gettime()从1970年1月1日起返回毫秒,因此。如果您有一个epoch时间戳,请通过乘以1000将其转换为javascript时间戳。
function epochToJsDate(ts){
// ts = epoch timestamp
// returns date obj
return new Date(ts*1000);
}
function jsDateToEpoch(d){
// d = javascript date obj
// returns epoch timestamp
return (d.getTime()-d.getMilliseconds())/1000;
}
#6
3
Are you just asking to convert a UTC string to a "local" string? You could do:
您是否只是要求将UTC字符串转换为“local”字符串?你能做的:
var utc_string = '2011-09-05 20:05:15';
var local_string = (function(dtstr) {
var t0 = new Date(dtstr);
var t1 = Date.parse(t0.toUTCString().replace('GMT', ''));
var t2 = (2 * t0) - t1;
return new Date(t2).toString();
})(utc_string);
#7
1
EDIT
编辑
var utcDate = new Date(incomingUTCepoch);
var date = new Date();
date.setUTCDate(utcDate.getDate());
date.setUTCHours(utcDate.getHours());
date.setUTCMonth(utcDate.getMonth());
date.setUTCMinutes(utcDate.getMinutes());
date.setUTCSeconds(utcDate.getSeconds());
date.setUTCMilliseconds(utcDate.getMilliseconds());
EDIT fixed
编辑固定
#8
1
If you prefer to resolve timestamps and dates conversions from and to UTC and local time without libraries like moment.js, take a look at the option below.
如果您喜欢在没有像moment这样的库的情况下解析来自UTC和本地时间的时间戳和日期转换。js,看看下面的选项。
For applications that use UTC timestamps, you may need to show the date in the browser considering the local timezone and daylight savings when applicable. Editing a date that is in a different daylight savings time even though in the same timezone can be tricky.
对于使用UTC时间戳的应用程序,您可能需要在浏览器中显示日期,考虑到本地时区和适用时的夏令时。即使在相同的时区,编辑一个在不同的夏令时时间的日期也是很困难的。
The Number
and Date
extensions below allow you to show and get dates in the timezone of the timestamps. For example, lets say you are in Vancouver, if you are editing a date in July or in December, it can mean you are editing a date in PST or PDT.
下面的数字和日期扩展允许您在时间戳的时区中显示和获取日期。例如,假设您在温哥华,如果您正在编辑7月或12月的日期,它可能意味着您正在编辑PST或PDT中的日期。
I recommend you to check the Code Snippet down below to test this solution.
我建议您检查下面的代码片段来测试这个解决方案。
Conversions from milliseconds
转换从毫秒
Number.prototype.toLocalDate = function () {
var value = new Date(this);
value.setHours(value.getHours() + (value.getTimezoneOffset() / 60));
return value;
};
Number.prototype.toUTCDate = function () {
var value = new Date(this);
value.setHours(value.getHours() - (value.getTimezoneOffset() / 60));
return value;
};
Conversions from dates
从日期转换
Date.prototype.getUTCTime = function () {
return this.getTime() - (this.getTimezoneOffset() * 60000);
};
Usage
使用
// Adds the timezone and daylight savings if applicable
(1499670000000).toLocalDate();
// Eliminates the timezone and daylight savings if applicable
new Date(2017, 6, 10).getUTCTime();
See it for yourself
看到你自己
// Extending Number
Number.prototype.toLocalDate = function () {
var value = new Date(this);
value.setHours(value.getHours() + (value.getTimezoneOffset() / 60));
return value;
};
Number.prototype.toUTCDate = function () {
var value = new Date(this);
value.setHours(value.getHours() - (value.getTimezoneOffset() / 60));
return value;
};
// Extending Date
Date.prototype.getUTCTime = function () {
return this.getTime() - (this.getTimezoneOffset() * 60000);
};
// Getting the demo to work
document.getElementById('m-to-local-button').addEventListener('click', function () {
var displayElement = document.getElementById('m-to-local-display'),
value = document.getElementById('m-to-local').value,
milliseconds = parseInt(value);
if (typeof milliseconds === 'number')
displayElement.innerText = (milliseconds).toLocalDate().toISOString();
else
displayElement.innerText = 'Set a value';
}, false);
document.getElementById('m-to-utc-button').addEventListener('click', function () {
var displayElement = document.getElementById('m-to-utc-display'),
value = document.getElementById('m-to-utc').value,
milliseconds = parseInt(value);
if (typeof milliseconds === 'number')
displayElement.innerText = (milliseconds).toUTCDate().toISOString();
else
displayElement.innerText = 'Set a value';
}, false);
document.getElementById('date-to-utc-button').addEventListener('click', function () {
var displayElement = document.getElementById('date-to-utc-display'),
yearValue = document.getElementById('date-to-utc-year').value || '1970',
monthValue = document.getElementById('date-to-utc-month').value || '0',
dayValue = document.getElementById('date-to-utc-day').value || '1',
hourValue = document.getElementById('date-to-utc-hour').value || '0',
minuteValue = document.getElementById('date-to-utc-minute').value || '0',
secondValue = document.getElementById('date-to-utc-second').value || '0',
year = parseInt(yearValue),
month = parseInt(monthValue),
day = parseInt(dayValue),
hour = parseInt(hourValue),
minute = parseInt(minuteValue),
second = parseInt(secondValue);
displayElement.innerText = new Date(year, month, day, hour, minute, second).getUTCTime();
}, false);
<link href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.11/semantic.css" rel="stylesheet"/>
<div class="ui container">
<p></p>
<h3>Milliseconds to local date</h3>
<input id="m-to-local" placeholder="Timestamp" value="0" /> <button id="m-to-local-button">Convert</button>
<em id="m-to-local-display">Set a value</em>
<h3>Milliseconds to UTC date</h3>
<input id="m-to-utc" placeholder="Timestamp" value="0" /> <button id="m-to-utc-button">Convert</button>
<em id="m-to-utc-display">Set a value</em>
<h3>Date to milliseconds in UTC</h3>
<input id="date-to-utc-year" placeholder="Year" style="width: 4em;" />
<input id="date-to-utc-month" placeholder="Month" style="width: 4em;" />
<input id="date-to-utc-day" placeholder="Day" style="width: 4em;" />
<input id="date-to-utc-hour" placeholder="Hour" style="width: 4em;" />
<input id="date-to-utc-minute" placeholder="Minute" style="width: 4em;" />
<input id="date-to-utc-second" placeholder="Second" style="width: 4em;" />
<button id="date-to-utc-button">Convert</button>
<em id="date-to-utc-display">Set the values</em>
</div>
#9
1
To convert the current epoch time in [ms] to a 24-hour time. You might need to specify the option to disable 12-hour format.
将[ms]的当前纪元时间转换为24小时。您可能需要指定禁用12小时格式的选项。
$ node.exe -e "var date = new Date(Date.now()); console.log(date.toLocaleString('en-GB', { hour12:false } ));"
2/7/2018, 19:35:24
or as JS:
或者JS:
var date = new Date(Date.now());
console.log(date.toLocaleString('en-GB', { hour12:false } ));
// 2/7/2018, 19:35:24
console.log(date.toLocaleString('en-GB', { hour:'numeric', minute:'numeric', second:'numeric', hour12:false } ));
// 19:35:24
Note: The use of en-GB
here, is just a (random) choice of a place using the 24 hour format, it is not your timezone!
注意:en-GB在这里的使用,只是使用24小时格式的一个(随机的)选择,它不是您的时区!
#10
0
@Amjad, good idea, but implemented poorly. Try
@Amjad,是个好主意,但实施得很糟糕。试一试
Date.prototype.setUTCTime = function(UTCTimestamp) {
var UTCDate = new Date(UTCTimestamp);
this.setUTCFullYear(UTCDate.getFullYear(), UTCDate.getMonth(), UTCDate.getDate());
this.setUTCHours(UTCDate.getHours(), UTCDate.getMinutes(), UTCDate.getSeconds(), UTCDate.getMilliseconds());
return this.getTime();
}
#11
0
Considering, you have epoch_time
available,
考虑到,你有epoch_time可用,
// for eg. epoch_time = 1487086694.213
var date = new Date(epoch_time * 1000); // multiply by 1000 for milliseconds
var date_string = date.toLocaleString('en-GB'); // 24 hour format
#12
0
First convert it to String and then replace the timezone text.
首先将其转换为字符串,然后替换时区文本。
function convertUnixTime(time) {
return new Date(time*1000).toString().replace("GMT+0530 (Sri Lanka Standard Time)","");
}