programing tip

new Date ()는 Chrome에서 작동하지만 Firefox에서는 작동하지 않습니다.

itbloger 2020. 9. 22. 07:47
반응형

new Date ()는 Chrome에서 작동하지만 Firefox에서는 작동하지 않습니다.


다음과 같은 datetime 문자열을 만들고 있습니다. 2010-07-15 11:54:21

그리고 다음 코드를 사용하면 Firefox에서 잘못된 날짜가 표시되지만 Chrome에서는 제대로 작동합니다.

var todayDateTime = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + seconds;
var date1 = new Date(todayDateTime);

파이어 폭스에서 date1은 나에게 유효하지 않은 날짜를 제공하지만 크롬에서는 잘 작동하며 주요 원인은 무엇입니까?


원하는 방식으로 날짜 개체를 인스턴스화 할 수 없습니다. 특정 방식이어야합니다. 다음은 몇 가지 유효한 예입니다.

new Date() // current date and time
new Date(milliseconds) //milliseconds since 1970/01/01
new Date(dateString)
new Date(year, month, day, hours, minutes, seconds, milliseconds)

또는

d1 = new Date("October 13, 1975 11:13:00")
d2 = new Date(79,5,24)
d3 = new Date(79,5,24,11,33,0)

Chrome은 더 유연해야합니다.

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

에서 apsillers의 코멘트 :

EMCAScript 사양 에는 정확히 하나의 날짜 형식 (예 : YYYY-MM-DDTHH : mm : ss.sssZ)이 필요하지만 사용자 지정 날짜 형식은 구현에서 자유롭게 지원 될 수 있습니다 . " 문자열이 [ECMAScript 정의] 형식을 따르지 않는 경우 이 함수는 구현 별 휴리스틱 또는 구현 별 날짜 형식으로 대체 될 수 있습니다. "Chrome과 FF는 단순히"구현 별 날짜 형식 "이 다릅니다.


이것은 모든 브라우저에서 작동합니다-

새 날짜 ( '2001/01/31 12:00:00 AM')

new Date('2001-01-31 12:00:00')

형식 : YYYY-MM-DDTHH : mm : ss.sss

세부 정보 : http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.1.15


이것은 대부분의 브라우저에서도 작동합니다.

new Date('2001/01/31 12:00:00')

그것은 형식입니다

"yyyy/MM/dd HH:mm:ss"

옵션 1 :

타임 스트링에 다음과 같은 형식이 있다고 가정합니다.

'2016-03-10 16:00:00.0'

이 경우 간단한 정규식을 수행하여 다음으로 변환 할 수 있습니다 ISO 8601.

'2016-03-10 16:00:00.0'.replace(/ /g,'T')

그러면 다음과 같은 출력이 생성됩니다.

'2016-03-10T16:00:00.0'

이것은 표준 datetime 형식이므로 모든 브라우저에서 지원됩니다.

document.body.innerHTML = new Date('2016-03-10T16:00:00.0') // THIS IS SAFE TO USE

옵션 2 :

타임 스트링에 다음과 같은 형식이 있다고 가정합니다.

'02-24-2015 09:22:21 PM'

여기에서 다음 정규식을 수행 할 수 있습니다.

'02-24-2015 09:22:21 PM'.replace(/-/g,'/');

이것 역시 모든 브라우저에서 지원하는 형식을 생성합니다.

document.body.innerHTML = new Date('02/24/2015 09:22:21 PM') // THIS IS SAFE TO USE

옵션 3 :

잘 지원되는 표준 중 하나로 조정하기 쉽지 않은 시간 문자열이 있다고 가정합니다.

이 경우 시간 문자열을 다른 조각으로 나누고 다음의 개별 매개 변수로 사용하는 것이 가장 좋습니다 Date.

document.body.innerHTML = new Date(2016, 2, 26, 3, 24, 0); // THIS IS SAFE TO USE


여전히 대시를 사용하여 날짜를 작성하려면 다음 형식을 사용할 수 있습니다.

var date = new Date('2013-08-31T17:00:00Z')

But bear in mind, that it creates time according to UTC. Meaning, if you live in GMT+3 (3 hours ahead of GMT) timezone, it will add this timezone offset to the time. So the above example will have this value, if GMT+3 (note that it is hour 20:00 and not 17:00):

Sat Aug 31 2013 20:00:00 GMT+0300 (FLE Standard Time)

Be sure to add 'Z' letter at the end, because otherwise Chrome and Firefox will parse the string differently (one will add time offset and the other won't).


I was having a similar issue in both Firefox and Safari when working with AngularJS. For example, if a date returned from Angular looked like this:

2014-06-02 10:28:00

using this code:

new Date('2014-06-02 10:28:00').toISOString();

returns an invalid date error in Firefox and Safari. However in Chrome it works fine. As another answer stated, Chrome is most likely just more flexible with parsing date strings.

My eventual goal was to format the date a certain way. I found an excellent library that handled both the cross browser compatibility issue and the date formatting issue. The library is called moment.js.

Using this library the following code works correctly across all browsers I tested:

moment('2014-06-02 10:28:00').format('MMM d YY')

If you are willing to include this extra library into your app you can more easily build your date string while avoiding possible browser compatibility issues. As a bonus you will have a good way to easily format, add, subtract, etc dates if needed.


This should work for you:

var date1 = new Date(year, month, day, hour, minute, seconds);

I had to create date form a string so I have done it like this:

var d = '2013-07-20 16:57:27';
var date1 = new Date(d.substr(0, 4), d.substr(5, 2), d.substr(8, 2), d.substr(11, 2), d.substr(14, 2), d.substr(17, 2));

Remember that the months in javascript are from 0 to 11, so you should reduce the month value by 1, like this:

var d = '2013-07-20 16:57:27';
var date1 = new Date(d.substr(0, 4), d.substr(5, 2) - 1, d.substr(8, 2), d.substr(11, 2), d.substr(14, 2), d.substr(17, 2));

One situation I've run into was when dealing with milliseconds. FF and IE will not parse this date string correctly when trying to create a new date. "2014/11/24 17:38:20.177Z" They do not know how to handle .177Z. Chrome will work though.


Simple Solution, This works with All Browsers,

var StringDate = "24-11-2017"   
var DateVar = StringDate.split("-");
var DateVal = new Date(DateVar[1] + "/" + DateVar[0] + "/" + DateVar[2]);
alert(DateVal);

In fact, Chrome is more flexible to deal with different string format. Even if you don't figure out its String format, Chrome still can successfully convert String to Date without error. Like this:

  var outputDate = new Date(Date.parse(inputString));

But for Firefox and Safari, things become more complex. In fact, in Firefox's document, it already says: (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse)

A string representing an RFC2822 or ISO 8601 date (other formats may be used, but results may be unexpected).

So, when you want to use Date.parse in Firefox and Safari, you should be careful. For me, I use a trick method to deal with it. (Note: it might be not always correct for all cases)

if (input.indexOf("UTC") != -1) {
  var tempInput = inputString.substr(0, 10) + "T" + inputString.substr(11, 8) + "Z";
  date = new Date(Date.parse(tempInput));
}

Here it converts 2013-08-08 11:52:18 UTC to 2013-08-08T11:52:18Z first, and then its format is fit words in Firefox's document. At this time, Date.parse will be always right in any browser.


In Firefox, any invalid Date is returned as a Date object as Date 1899-11-29T19:00:00.000Z, therefore check if browser is Firefox then get Date object of string "1899-11-29T19:00:00.000Z".getDate(). Finally compare it with the date.


I have used following date format and it's working in all browser.

var target_date = new Date("Jul 17, 2015 16:55:22").getTime();

var days, hours, minutes, seconds;

var countdown = document.getElementById("countdown");

remaining = setInterval(function () {

    var current_date = new Date().getTime();
    var seconds_left = (target_date - current_date) / 1000;
    days = parseInt(seconds_left / 86400);
    seconds_left = seconds_left % 86400;
    hours = parseInt(seconds_left / 3600);
    seconds_left = seconds_left % 3600;
    minutes = parseInt(seconds_left / 60);
    seconds = parseInt(seconds_left % 60);
    countdown.innerHTML = "<b>"+days + " day, " + hours + " hour, "
        + minutes + " minute, " + seconds + " second.</b>";  
}, 1000);

참고URL : https://stackoverflow.com/questions/3257460/new-date-is-working-in-chrome-but-not-firefox

반응형