programing tip

시간대 자바 스크립트없이 날짜 구문 분석

itbloger 2020. 7. 17. 20:56
반응형

시간대 자바 스크립트없이 날짜 구문 분석


JavaScript에서 시간대없이 날짜를 구문 분석하고 싶습니다. 나는 시도했다 :

new Date(Date.parse("2005-07-08T00:00:00+0000"));

반품 2005 년 7 월 8 일 02:00:00 GMT + 0200 (중부 유럽 일광 절약 시간)

new Date(Date.parse("2005-07-08 00:00:00 GMT+0000"));

동일한 결과를 반환

new Date(Date.parse("2005-07-08 00:00:00 GMT-0000"));

동일한 결과를 반환

시간을 파싱하고 싶습니다.

  1. 시간대가 없습니다.

  2. 생성자 Date.UTC 또는 new Date (년, 월, 일)를 호출하지 않습니다.

  3. 프로토 타입에 접근하지 않고 문자열을 Date 생성자에 간단하게 전달하십시오.

  4. 제품이 Date아닌 제품을 사용해야 합니다 String.


날짜가 올바르게 구문 분석되었습니다. 현지 시간대로 변환하는 것은 toString입니다.

let s = "2005-07-08T11:22:33+0000";
let d = new Date(Date.parse(s));

// this logs for me 
// "Fri Jul 08 2005 13:22:33 GMT+0200 (Central European Summer Time)" 
// and something else for you

console.log(d.toString()) 

// this logs
// Fri, 08 Jul 2005 11:22:33 GMT
// for everyone

console.log(d.toUTCString())

Javascript Date 객체는 타임 스탬프입니다. 에포크 이후 몇 밀리 초 만 포함되어 있습니다. Date 객체에는 시간대 정보가 없습니다. 이 타임 스탬프가 나타내는 달력 날짜 (일, 분, 초)는 해석의 문제입니다 ( to...String방법 중 하나 ).

위의 예는 날짜가 올바르게 구문 분석되고 있음을 나타냅니다. 즉, 실제로는 GMT의 "2005-07-08T11 : 22 : 33"에 해당하는 양의 밀리 초를 포함합니다.


나는 같은 문제가 있습니다. 날짜를 문자열로 가져옵니다 (예 : '2016-08-25T00 : 00 : 00').하지만 정확한 시간의 Date 객체가 필요합니다. String을 객체로 변환하려면 getTimezoneOffset을 사용하십시오.

var date = new Date('2016-08-25T00:00:00')
var userTimezoneOffset = date.getTimezoneOffset() * 60000;
new Date(date.getTime() - userTimezoneOffset);

getTimezoneOffset()에테르 음수 또는 양수 값을 반환합니다. 세계의 모든 위치에서 작동하려면이 값을 빼야합니다.


나는 같은 문제에 부딪 쳤고 내가 작업했던 레거시 프로젝트와 그들이이 문제를 어떻게 처리했는지에 대해 이상한 것을 기억했다. 나는 당시에 그것을 이해하지 못했고 문제를 직접 만날 때까지 실제로 신경 쓰지 않았습니다.

var date = '2014-01-02T00:00:00.000Z'
date = date.substring(0,10).split('-')
date = date[1] + '-' + date[2] + '-' + date[0]

new Date(date) #Thu Jan 02 2014 00:00:00 GMT-0600

어떤 이유로 든 '01 -02-2014 '로 날짜를 전달하면 시간대가 0으로 설정되고 사용자의 시간대는 무시됩니다. 이것은 Date 클래스의 우연 일 수 있지만 얼마 전에 존재했으며 오늘 존재합니다. 그리고 브라우저 간 작동하는 것 같습니다. 직접 해보십시오.

이 코드는 시간대가 중요하지만 날짜를보고있는 사람이 소개 된 정확한 순간에 관심이없는 글로벌 프로젝트에서 구현됩니다.


Date객체 자체가 어쨌든 시간대가 포함되며, 반환 된 결과는 기본 방법으로 문자열로 변환하는 효과입니다. 즉, 시간대가 없으면 날짜 객체 만들 수 없습니다 . 그러나 당신이 할 수있는 일은 Date자신의 것을 만들어서 객체 의 행동을 모방하는 것입니다. 그러나 이것은 moment.js 와 같은 라이브러리로 넘겨주는 것이 좋습니다 .


간단한 해결책

const handler1 = {
  construct(target, args) {
    let newDate = new target(...args);
    var tzDifference = newDate.getTimezoneOffset();
    return new target(newDate.getTime() + tzDifference * 60 * 1000);
  }
};

Date = new Proxy(Date, handler1);

일반적인 메모입니다. 유연성을 유지하는 방법.

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

getMinutes ()를 사용할 수 있지만 처음 9 분 동안 하나의 숫자 만 반환합니다.

let epoch = new Date() // Or any unix timestamp

let za = new Date(epoch),
    zaR = za.getUTCFullYear(),
    zaMth = za.getUTCMonth(),
    zaDs = za.getUTCDate(),
    zaTm = za.toTimeString().substr(0,5);

console.log(zaR +"-" + zaMth + "-" + zaDs, zaTm)

Date.prototype.getDate()
    Returns the day of the month (1-31) for the specified date according to local time.
Date.prototype.getDay()
    Returns the day of the week (0-6) for the specified date according to local time.
Date.prototype.getFullYear()
    Returns the year (4 digits for 4-digit years) of the specified date according to local time.
Date.prototype.getHours()
    Returns the hour (0-23) in the specified date according to local time.
Date.prototype.getMilliseconds()
    Returns the milliseconds (0-999) in the specified date according to local time.
Date.prototype.getMinutes()
    Returns the minutes (0-59) in the specified date according to local time.
Date.prototype.getMonth()
    Returns the month (0-11) in the specified date according to local time.
Date.prototype.getSeconds()
    Returns the seconds (0-59) in the specified date according to local time.
Date.prototype.getTime()
    Returns the numeric value of the specified date as the number of milliseconds since January 1, 1970, 00:00:00 UTC (negative for prior times).
Date.prototype.getTimezoneOffset()
    Returns the time-zone offset in minutes for the current locale.
Date.prototype.getUTCDate()
    Returns the day (date) of the month (1-31) in the specified date according to universal time.
Date.prototype.getUTCDay()
    Returns the day of the week (0-6) in the specified date according to universal time.
Date.prototype.getUTCFullYear()
    Returns the year (4 digits for 4-digit years) in the specified date according to universal time.
Date.prototype.getUTCHours()
    Returns the hours (0-23) in the specified date according to universal time.
Date.prototype.getUTCMilliseconds()
    Returns the milliseconds (0-999) in the specified date according to universal time.
Date.prototype.getUTCMinutes()
    Returns the minutes (0-59) in the specified date according to universal time.
Date.prototype.getUTCMonth()
    Returns the month (0-11) in the specified date according to universal time.
Date.prototype.getUTCSeconds()
    Returns the seconds (0-59) in the specified date according to universal time.
Date.prototype.getYear()
    Returns the year (usually 2-3 digits) in the specified date according to local time. Use getFullYear() instead. 

이 코드를 사용할 수 있습니다

var stringDate = "2005-07-08T00:00:00+0000";
var dTimezone = new Date();
var offset = dTimezone.getTimezoneOffset() / 60;
var date = new Date(Date.parse(stringDate));
date.setHours(date.getHours() + offset);

이것이 나를 위해 일하는이 문제에 대해 생각해 낸 해결책입니다.


사용 된 라이브러리 : 일반 자바 스크립트 Date 클래스가있는 momentjs.

Step 1. Convert String date to moment object (PS: moment retains the original date and time as long as toDate() method is not called):

const dateMoment = moment("2005-07-08T11:22:33+0000");

Step 2. Extract hours and minutes values from the previously created moment object:

  const hours = dateMoment.hours();
  const mins = dateMoment.minutes();

Step 3. Convert moment to Date(PS: this will change the original date based on the timezone of your browser/machine, but don't worry and read step 4.):

  const dateObj = dateMoment.toDate();

Step 4. Manually set the hours and minutes extracted in Step 2.

  dateObj.setHours(hours);
  dateObj.setMinutes(mins);

Step 5. dateObj will now have show the original Date without any timezone difference. Even the Daylight time changes won't have any effect on the date object as we are manually setting the original hours and minutes.

Hope this helps.


(new Date().toString()).replace(/ \w+-\d+ \(.*\)$/,"")

This will have output: Tue Jul 10 2018 19:07:11

(new Date("2005-07-08T11:22:33+0000").toString()).replace(/ \w+-\d+ \(.*\)$/,"")

This will have output: Fri Jul 08 2005 04:22:33

Note: The time returned will depend on your local timezone


There are some inherent problems with date parsing that are unfortunately not addressed well by default.

-Human readable dates have implicit timezone in them
-There are many widely used date formats around the web that are ambiguous

To solve these problems easy and clean one would need a function like this:

>parse(whateverDateTimeString,expectedDatePattern,timezone)
"unix time in milliseconds"

I have searched for this, but found nothing like that!

So I created: https://github.com/zsoltszabo/timestamp-grabber

Enjoy!

참고URL : https://stackoverflow.com/questions/17545708/parse-date-without-timezone-javascript

반응형