development

JavaScript에서 UTC 타임 스탬프를 어떻게 얻습니까?

big-blog 2020. 6. 18. 07:25
반응형

JavaScript에서 UTC 타임 스탬프를 어떻게 얻습니까?


웹 애플리케이션을 작성하는 동안 DB에 모든 날짜 시간을 UTC 타임 스탬프 로 저장 (서버 측)하는 것이 좋습니다.

JavaScript의 시간대 조작 측면에서 많은 것을 할 수 없다는 것을 알았을 때 놀랐습니다.

Date 객체를 약간 확장했습니다. 이 기능이 의미가 있습니까? 기본적으로 서버에 무엇이든 보낼 때 마다이 기능으로 포맷 된 타임 스탬프가됩니다 ...

여기에 큰 문제가 있습니까? 아니면 다른 각도의 솔루션입니까?

Date.prototype.getUTCTime = function(){ 
  return new Date(
    this.getUTCFullYear(),
    this.getUTCMonth(),
    this.getUTCDate(),
    this.getUTCHours(),
    this.getUTCMinutes(), 
    this.getUTCSeconds()
  ).getTime(); 
}

그것은 나에게 조금 복잡해 보입니다. 그리고 성능에 대해서도 확신이 없습니다.


  1. 이러한 방식으로 생성 된 날짜는 현지 시간대를 사용하여 생성 된 날짜를 잘못 만듭니다. 특정 날짜 객체의 시간대를 설정하려면 시간대를 포함하는 날짜 문자열에서 시간대를 생성해야합니다. (이전 Android 브라우저에서 작동하게하는 데 문제가있었습니다.)

  2. getTime()평 초가 아닌 밀리 초 반환합니다.

UTC / Unix 타임 스탬프의 경우 다음과 같이 충분합니다.

Math.floor((new Date()).getTime() / 1000)

현재 시간대 오프셋을 결과에 반영합니다. 문자열 표현의 경우 David Ellis의 답변이 효과가 있습니다.

명확히하기 위해 :

new Date(Y, M, D, h, m, s)

해당 입력은 현지 시간으로 처리됩니다 . 경우 UTC 시간이 전달되고, 결과는 다를 수 있습니다. 관찰하십시오 (현재 GMT +02 : 00에 있으며 07:50입니다).

> var d1 = new Date();
> d1.toUTCString();
"Sun, 18 Mar 2012 05:50:34 GMT" // two hours less than my local time
> Math.floor(d1.getTime()/ 1000)
1332049834 

> var d2 = new Date( d1.getUTCFullYear(), d1.getUTCMonth(), d1.getUTCDate(), d1.getUTCHours(), d1.getUTCMinutes(), d1.getUTCSeconds() );
> d2.toUTCString();
"Sun, 18 Mar 2012 03:50:34 GMT" // four hours less than my local time, and two hours less than the original time - because my GMT+2 input was interpreted as GMT+0!
> Math.floor(d2.getTime()/ 1000)
1332042634

또한 getUTCDate()로 대체 할 수 없습니다 getUTCDay(). 그 달의 날짜를getUTCDate() 반환 하기 때문입니다 . 반면 요일을 반환 합니다 .getUTCDay()


getTimezoneOffset 및 getTime을 사용하여 수행 할 수도 있습니다.

x = new Date()
var UTCseconds = (x.getTime() + x.getTimezoneOffset()*60*1000)/1000;

console.log("UTCseconds", UTCseconds)


일반적인 형식으로 UTC 시간을 얻는 가장 쉬운 방법은 다음과 같습니다.

new Date().toISOString()
"2016-06-03T23:15:33.008Z"

일반적으로 클라이언트 측에서 "시간대 조작"을 많이 수행 할 필요는 없습니다. 원칙적으로 난의 형태로 UTC 날짜와 저장 및 작업에 시도 ticks"또는 1970 년 1 월 1 일 자정 이후의 밀리 초 수를 ." 이를 통해 스토리지, 정렬, 오프셋 계산을 단순화하고 무엇보다도 "일광 절약 시간"조정의 어려움을 없애줍니다. 여기 내가 사용하는 작은 JavaScript 코드가 있습니다.

현재 UTC 시간을 얻으려면

function getCurrentTimeUTC()
{
    //RETURN:
    //      = number of milliseconds between current UTC time and midnight of January 1, 1970
    var tmLoc = new Date();
    //The offset is in minutes -- convert it to ms
    return tmLoc.getTime() + tmLoc.getTimezoneOffset() * 60000;
}

그런 다음 일반적으로 필요한 것은 최종 사용자의 날짜 / 시간을 현지 시간대 및 형식으로 지정하는 것입니다. 다음은 클라이언트 컴퓨터의 모든 날짜 및 시간 형식 복잡성을 처리합니다.

function formatDateTimeFromTicks(nTicks)
{
    //'nTicks' = number of milliseconds since midnight of January 1, 1970
    //RETURN:
    //      = Formatted date/time
    return new Date(nTicks).toLocaleString();
}

function formatDateFromTicks(nTicks)
{
    //'nTicks' = number of milliseconds since midnight of January 1, 1970
    //RETURN:
    //      = Formatted date
    return new Date(nTicks).toLocaleDateString();
}

function formatTimeFromTicks(nTicks)
{
    //'nTicks' = number of milliseconds since midnight of January 1, 1970
    //RETURN:
    //      = Formatted time
    return new Date(nTicks).toLocaleTimeString();
}

따라서 다음 예제는

var ticks = getCurrentTimeUTC();  //Or get it from the server

var __s = "ticks=" + ticks + 
    ", DateTime=" + formatDateTimeFromTicks(ticks) +
    ", Date=" + formatDateFromTicks(ticks) +
    ", Time=" + formatTimeFromTicks(ticks);

document.write("<span>" + __s + "</span>");

다음을 반환합니다 (미국 영어 로캘).

틱 = 1409103400661, DateTime = 8 / 26 / 2014 6:36:40 PM, Date = 8 / 26 / 2014, 시간 = 6 : 36 : 40 PM


I actually think Date values in js are far better than say the C# DateTime objects. The C# DateTime objects have a Kind property, but no strict underlying time zone as such, and time zone conversions are difficult to track if you are converting between two non UTC and non local times. In js, all Date values have an underlying UTC value which is passed around and known regardless of the offest or time zone conversions that you do. My biggest complaint about the Date object is the amount of undefined behaviour that browser implementers have chosen to include, which can confuse people who attack dates in js with trial and error than reading the spec. Using something like iso8601.js solves this varying behaviour by defining a single implementation of the Date object.

By default, the spec says you can create dates with an extended ISO 8601 date format like

var someDate = new Date('2010-12-12T12:00Z');

So you can infer the exact UTC time this way.

When you want to pass the Date value back to the server you would call

someDate.toISOString();

or if you would rather work with a millisecond timestamp (number of milliseconds from the 1st January 1970 UTC)

someDate.getTime();

ISO 8601 is a standard. You can't be confused about what a date string means if you include the date offset. What this means for you as a developer is that you never have to deal with local time conversions yourself. The local time values exist purely for the benefit of the user, and date values by default display in their local time. All the local time manipulations allow you to display something sensible to the user and to convert strings from user input. It's good practice to convert to UTC as soon as you can, and the js Date object makes this fairly trivial.

On the downside there is not a lot of scope for forcing the time zone or locale for the client (that I am aware of), which can be annoying for website-specific settings, but I guess the reasoning behind this is that it's a user configuration that shouldn't be touched.

So, in short, the reason there isn't a lot of native support for time zone manipulation is because you simply don't want to be doing it.


If you want a one liner, The UTC Unix Timestamp can be created in JavaScript as:

var currentUnixTimestap = ~~(+new Date() / 1000);

This will take in account the timezone of the system. It is basically time elapsed in Seconds since epoch.

How it works:

  • Create date object : new Date().
  • Convert to timestamp by adding unary + before object creation to convert it to timestamp integer. : +new Date().
  • Convert milliseconds to seconds: +new Date() / 1000
  • Use double tildes to round off the value to integer. : ~~(+new Date())

I use the following:

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

Once defined this method you can do:

var utcTime = new Date().getUTCTime();

I think this is a better solution

// UTC milliseconds
new Date(Date.now()+(new Date().getTimezoneOffset()*60000)).getTime()

// UTC seconds
new Date(Date.now()+(new Date().getTimezoneOffset()*60000)).getTime()/1000|0

Since new Date().toUTCString()returns a string like "Wed, 11 Oct 2017 09:24:41 GMT" you can slice the last 3 characters and pass the sliced string to new Date():

new Date()
// Wed Oct 11 2017 11:34:33 GMT+0200 (CEST)

new Date(new Date().toUTCString().slice(0, -3))
// Wed Oct 11 2017 09:34:33 GMT+0200 (CEST)

EDIT: The code below does NOT work. I was always assuming that new Date().getTime() returned the number of seconds since the 1st of January 1970 IN THE CURRENT TIMEZONE. This is not the case: getTime() returns the number of seconds in UTC. So, the code below does gross over-adjusting. Thank you everybody!]

First of all, thank you for your fantastic insights. I guess my question had the wrong title... it should have been "Get the UTC Unix Timestamp for an existing date".

So, if I have a date object:

var d = new Date(2009,01,31)

I was after a function that would tell me "The UTC Unix Timestamp".

This function seems to be the real trick:

Date.prototype.getUTCUnixTime =  function (){
  return Math.floor( new Date(
    this.getUTCFullYear(),
    this.getUTCMonth(),
    this.getUTCDate(),
    this.getUTCHours(),
    this.getUTCMinutes(), 
    this.getUTCSeconds()
  ).getTime() / 1000); 
}

Note that it works on "this" This means that I can do:

var n = new Date(2008,10,10)
...
...

n.getUTCUnixTime();

And get the number of seconds since the 1st of Jan 1970 in Unix time. Right?

It's a little insane, to me, that Javascript stores everything in UTC times, but then in order to get that number I have to create a new Date object passing the individual UTC getters and then finally call getTime() for that...

Merc.


I am amazed at how complex this question has become.

These are all identical, and their integer values all === EPOCH time :D

console.log((new Date()).getTime() / 1000, new Date().valueOf() / 1000, (new Date() - new Date().getTimezoneOffset() * 60 * 1000) / 1000);

Do not believe me, checkout: http://www.epochconverter.com/


I want to make clear that new Date().getTime() does in fact return a UTC value, so it is a really helpful way to store and manage dates in a way that is agnostic to localized times.

In other words, don't bother with all the UTC javascript functions. Instead, just use Date.getTime().

More info on the explanation is here: If javascript "(new Date()).getTime()" is run from 2 different Timezones.


I think this what you are expecting...

var currTimestamp = Date.now(), //1482905176396
    utcDateString = (new Date(currTimestamp)).toUTCString(); //"Wed, 28 Dec 2016 06:06:50 GMT"

Now,

new Date(utcDateString).getTime(); //This will give you UTC Timestamp in JavaScript

This will return the timestamp in UTC:

var utc = new Date(new Date().toUTCString()).getTime();

참고URL : https://stackoverflow.com/questions/9756120/how-do-i-get-a-utc-timestamp-in-javascript

반응형