将 UTC 纪元转换为本地日期

发布于 2024-10-10 15:17:43 字数 520 浏览 11 评论 0原文

我已经为此奋斗了一段时间了。我正在尝试将纪元转换为日期对象。该纪元以 UTC 格式发送给我。每当您传递 new Date() 一个纪元时,它都会假定它是本地纪元。我尝试创建一个 UTC 对象,然后使用 setTime() 将其调整到正确的纪元,但唯一有用的方法是 toUTCString() 而字符串则不然帮我。如果我将该字符串传递给一个新日期,它应该注意到它是 UTC,但事实并非如此。

new Date( new Date().toUTCString() ).toLocaleString()

我的下一个尝试是尝试获取本地当前纪元和 UTC 当前纪元之间的差异,但我也无法获取。

new Date( new Date().toUTCString() ).getTime() - new Date().getTime()

它只给我带来非常小的差异,不到 1000,以毫秒为单位。

有什么建议吗?

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.

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.

new Date( new Date().toUTCString() ).getTime() - new Date().getTime()

It’s only giving me very small differences, under 1000, which is in milliseconds.

Any suggestions?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(18

等风也等你 2024-10-17 15:17:43

我想我有一个更简单的解决方案——将初始日期设置为纪元并添加 UTC 单位。假设您有一个以秒为单位存储的 UTC 纪元变量。 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 现在是一个日期(在我的时区中),设置为 Fri Feb 13 2009 18:31:30 GMT-0500 (EST )

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:

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)

朱染 2024-10-17 15:17:43

这很简单,new Date()只需要几毫秒,例如

new Date(1394104654000)
> Thu Mar 06 2014 06:17:34 GMT-0500 (EST)

It's easy, new Date() just takes milliseconds, e.g.

new Date(1394104654000)
> Thu Mar 06 2014 06:17:34 GMT-0500 (EST)
仲春光 2024-10-17 15:17:43

纪元时间以 1970 年 1 月 1 日开始的为单位。date.getTime() 返回 1970 年 1 月 1 日开始的毫秒,所以..如果您有纪元时间戳,请将其乘以 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;
   }

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.

   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;
   }
携君以终年 2024-10-17 15:17:43

只是为了日志,我使用 Moment.js 库来完成此操作,我是无论如何用于格式化。

moment.utc(1234567890000).local()
>Fri Feb 13 2009 19:01:30 GMT-0430 (VET)

And just for the logs, I did this using Moment.js library, which I was using for formatting anyway.

moment.utc(1234567890000).local()
>Fri Feb 13 2009 19:01:30 GMT-0430 (VET)
沫离伤花 2024-10-17 15:17:43
 function ToLocalDate (inDate) {
    var date = new Date();
    date.setTime(inDate.valueOf() - 60000 * inDate.getTimezoneOffset());
    return date;
}
 function ToLocalDate (inDate) {
    var date = new Date();
    date.setTime(inDate.valueOf() - 60000 * inDate.getTimezoneOffset());
    return date;
}
度的依靠╰つ 2024-10-17 15:17:43

纪元时间(即 Unix 纪元时间)几乎总是自 1970 年 1 月 1 日 00:00:00(UTC 时间)以来过期的数,而不是毫秒数> 这里的一些答案已经暗示了这一点。

https://en.wikipedia.org/wiki/Unix_time

因此,如果您获得了Unix 纪元时间值可能以秒为单位,看起来类似于 1547035195。如果您想让 JavaScript 中的人类可读,您需要将该值转换为毫秒,并将该值传递到 Date(value) 构造函数中,例如:

const unixEpochTimeMS = 1547035195 * 1000;
const d = new Date(unixEpochTimeMS);
// Careful, the string output here can vary by implementation...
const strDate = d.toLocaleString();

您不需要执行 < code>d.setUTCMilliseconds(0) 步骤在接受的答案中,因为 JavaScript Date(value) 构造函数采用以毫秒为单位的 UTC 值(而不是本地时间) )。

https://developer.mozilla.org/en -US/docs/Web/JavaScript/Reference/Global_Objects/Date#Syntax

另请注意,您应该避免使用采用字符串日期时间表示形式的 Date(...) 构造函数,这不推荐(参见上面的链接)。

Epoch time (i.e. Unix Epoch time) is nearly always the number of seconds that have expired since 1st Jan 1970 00:00:00 (UTC time), not the number of milliseconds which some of the answers here have implied.

https://en.wikipedia.org/wiki/Unix_time

Therefore, if you have been given a Unix Epoch time value it will probably be in seconds, and will look something like 1547035195. If you want to make this human readable in JavaScript, you need to convert the value to milliseconds, and pass that value into the Date(value) constructor, e.g.:

const unixEpochTimeMS = 1547035195 * 1000;
const d = new Date(unixEpochTimeMS);
// Careful, the string output here can vary by implementation...
const strDate = d.toLocaleString();

You don't need to do the d.setUTCMilliseconds(0) step in the accepted answer because the JavaScript Date(value) constructor takes a UTC value in milliseconds (not a local time).

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#Syntax

Also note that you should avoid using the Date(...) constructor that takes a string datetime representation, this is not recommended (see the link above).

空袭的梦i 2024-10-17 15:17:43

var myDate = new Date(your epoch date *1000);

来源 - https: //www.epochconverter.com/programming/#javascript

var myDate = new Date( your epoch date *1000);

source - https://www.epochconverter.com/programming/#javascript

捶死心动 2024-10-17 15:17:43

最简单的方法

如果你有以毫秒为单位的unix纪元,在我的例子中 - 1601209912824

  1. 将其转换为日期对象作为
const dateObject = new Date(milliseconds)
const humanDateFormat = dateObject.toString() 

输出 -

Sun Sep 27 2020 18:01:52 GMT+0530 (India Standard Time)
  1. 如果你想要 UTC 格式的日期 -
const dateObject = new Date(milliseconds)
const humanDateFormat = dateObject.toUTCString() 
  1. 现在你可以随意格式化它。

The Easiest Way

If you have the unix epoch in milliseconds, in my case - 1601209912824

  1. convert it into a Date Object as so
const dateObject = new Date(milliseconds)
const humanDateFormat = dateObject.toString() 

output -

Sun Sep 27 2020 18:01:52 GMT+0530 (India Standard Time)
  1. if you want the date in UTC -
const dateObject = new Date(milliseconds)
const humanDateFormat = dateObject.toUTCString() 
  1. Now you can format it as you please.
以往的大感动 2024-10-17 15:17:43

将当前纪元时间(以 [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

或如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

注意:这里使用en-GB,只是(随机)选择一个使用24小时格式的地方,它不是你的时区!

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.

$ 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:

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!

我的影子我的梦 2024-10-17 15:17:43

除了 @djechlin 的上述答案之外,

d = '1394104654000';
new Date(parseInt(d));

还将 EPOCH 时间转换为人类可读的日期。只是不要忘记 EPOCH 时间类型必须是整数。

Addition to the above answer by @djechlin

d = '1394104654000';
new Date(parseInt(d));

converts EPOCH time to human readable date. Just don't forget that type of EPOCH time must be an Integer.

静赏你的温柔 2024-10-17 15:17:43

我发现的最简单的解决方案是:

var timestamp = Date.now(), // returns milliseconds since epoch time
    normalisedTime = new Date(timestamp);

注意,在 new Date(timestamp) 语句末尾没有 * 1000 ,因为这样(对我来说无论如何!)似乎总是给出错误的日期,即不是给出 2019 年,而是给出年份 51015,所以请记住这一点。

The simplest solution I've found to this, is:

var timestamp = Date.now(), // returns milliseconds since epoch time
    normalisedTime = new Date(timestamp);

Notice this doesn't have the * 1000 at the end of new Date(timestamp) statement as this (for me anyway!) always seems to give out the wrong date, ie instead of giving the year 2019 it gives the year as 51015, so just bear that in mind.

嘿哥们儿 2024-10-17 15:17:43

考虑到,您有 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

Considering, you have epoch_time available,

// 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
注定孤独终老 2024-10-17 15:17:43

编辑

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

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

ぇ气 2024-10-17 15:17:43

您只是要求将 UTC 字符串转换为“本地”字符串吗?你可以这样做:

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);

Are you just asking to convert a UTC string to a "local" string? You could do:

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);
银河中√捞星星 2024-10-17 15:17:43

如果您希望在不使用 moment.js 等库的情况下解决 UTC 和本地时间之间的时间戳和日期转换问题,请查看下面的选项。

对于使用 UTC 时间戳的应用程序,您可能需要在浏览器中显示日期,并考虑当地时区和夏令时(如果适用)。即使位于同一时区,编辑处于不同夏令时的日期也可能很棘手。

下面的 NumberDate 扩展允许您显示和获取时间戳所在时区中的日期。例如,假设您在温哥华,如果您正在编辑 7 月或 12 月的日期,则可能意味着您正在编辑 PST 或 PDT 的日期。

我建议您查看下面的代码片段来测试此解决方案。

从毫秒开始的转换

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;
};

从日期开始的转换

Date.prototype.getUTCTime = function () {
    return this.getTime() - (this.getTimezoneOffset() * 60000);
};

用法

// Adds the timezone and daylight savings if applicable
(1499670000000).toLocalDate();

// Eliminates the timezone and daylight savings if applicable
new Date(2017, 6, 10).getUTCTime();

亲自看看

// 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>

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.

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.

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.

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>

々眼睛长脚气 2024-10-17 15:17:43

我已经使用 Intl.DateTimeFormat() 转换了纪元时间。输入时间以毫秒为单位。

这是我使用的代码示例:

let options = {
  year: "numeric",
  month: "numeric",
  day: "numeric",
  hour: "numeric",
  minute: "numeric",
  second: "numeric",
  hour12: false,
  timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
};

export const epochTime = (time) => { 
  return new Intl.DateTimeFormat("en-US", options).format(new Date(time)); // returns DD/MM/YYYY hh:mm ss
};

参考资料:

  1. https: //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl
  2. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat

I have converted the epoch time by using Intl.DateTimeFormat(). The input time is in milliseconds.

here is code example that I used:

let options = {
  year: "numeric",
  month: "numeric",
  day: "numeric",
  hour: "numeric",
  minute: "numeric",
  second: "numeric",
  hour12: false,
  timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
};

export const epochTime = (time) => { 
  return new Intl.DateTimeFormat("en-US", options).format(new Date(time)); // returns DD/MM/YYYY hh:mm ss
};

References:

  1. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl
  2. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat
农村范ル 2024-10-17 15:17:43

不使用 Moment 将 Epoch 转换为特定日期格式的简单方法

const epochTime = 1697054700000; 
const d = new Date(epochTime);
const date = d.toJSON(); //This will return -->> 2023-10-11T20:05:00.000Z
const date = d.toLocaleDateString(); //This will return -->> 10/24/2023

Simple way to convert Epoch to Specific date format without using Moment

const epochTime = 1697054700000; 
const d = new Date(epochTime);
const date = d.toJSON(); //This will return -->> 2023-10-11T20:05:00.000Z
const date = d.toLocaleDateString(); //This will return -->> 10/24/2023
挽心 2024-10-17 15:17:43

@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();
}

@Amjad, good idea, but a better implementation would be:

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();
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文