IT

사용자의 로캘 형식 및 시간 오프셋으로 날짜 / 시간 표시

lottoking 2020. 6. 5. 08:11
반응형

사용자의 로캘 형식 및 시간 오프셋으로 날짜 / 시간 표시


서버가 항상 HTML로 UTC로 날짜를 제공하고 클라이언트 사이트의 JavaScript가 사용자의 현지 시간대로 변환하도록하고 싶습니다.

사용자의 로캘 날짜 형식으로 출력 할 수있는 경우 보너스.


UTC 날짜로 시작하는 가장 확실한 방법은 새 Date객체 를 만들고 setUTC…메소드를 사용하여 원하는 날짜 / 시간으로 설정하는 것입니다.

그런 다음 다양한 toLocale…String방법으로 현지화 된 출력을 제공합니다.

예:

// This would come from the server.
// Also, this whole block could probably be made into an mktime function.
// All very bare here for quick grasping.
d = new Date();
d.setUTCFullYear(2004);
d.setUTCMonth(1);
d.setUTCDate(29);
d.setUTCHours(2);
d.setUTCMinutes(45);
d.setUTCSeconds(26);

console.log(d);                        // -> Sat Feb 28 2004 23:45:26 GMT-0300 (BRT)
console.log(d.toLocaleString());       // -> Sat Feb 28 23:45:26 2004
console.log(d.toLocaleDateString());   // -> 02/28/2004
console.log(d.toLocaleTimeString());   // -> 23:45:26

일부 참고 문헌 :


새 프로젝트의 경우 moment.js를 사용 하십시오.

이 질문은 꽤 오래되었으므로 당시에moment.js 가 존재하지 않았지만 새로운 프로젝트의 경우 이와 같은 작업을 단순화합니다.

UTC에서 날짜 문자열을 다음과 같이 구문 분석하는 것이 가장 좋습니다 ( 모든 브라우저에서 일관된 결과를 얻으려면 서버에서 ISO-8601 호환 문자열을 작성하십시오).

var m = moment("2013-02-08T09:30:26Z");

이제 m응용 프로그램에서 사용 하십시오. moment.js는 기본적으로 표시 작업을위한 현지 시간대입니다. 날짜 및 시간 값을 형식화 하거나 그 일부를 추출 하는 방법 에는 여러 가지 가 있습니다.

다음과 같이 사용자 로케일에서 moment 객체를 포맷 할 수도 있습니다.

m.format('LLL') // Returns "February 8 2013 8:30 AM" on en-us

moment.js 객체를 다른 시간대로 변환하려면 (즉, 로컬 시간대 나 UTC가 아닌) moment.js 시간대 확장 이 필요합니다 . 이 페이지에는 몇 가지 예가 있으며 사용하기가 매우 간단합니다.


new Date().getTimezoneOffset()/60시간대에 사용할 수 있습니다 . toLocaleString()사용자의 로캘을 사용하여 날짜를 표시 하는 방법 도 있습니다 .

전체 목록은 다음과 같습니다. 날짜 작업


날짜 개체가 생성되면 다음은 전환을위한 스 니펫입니다.

이 함수는 UTC 형식의 Date 객체와 형식 문자열을 사용합니다. 프로토 타입
이 필요합니다 Date.strftime.

function UTCToLocalTimeString(d, format) {
    if (timeOffsetInHours == null) {
        timeOffsetInHours = (new Date().getTimezoneOffset()/60) * (-1);
    }
    d.setHours(d.getHours() + timeOffsetInHours);

    return d.strftime(format);
}

JS에서는 위에서 언급 한 것처럼 각 속성을 변환하지 않고 로컬 날짜 시간을 형식화하는 간단하고 크로스 플랫폼 방법이 없습니다.

다음은 로컬 YYYY-MM-DD를 얻는 데 사용하는 빠른 해킹입니다. 최종 날짜에 더 이상 올바른 시간대가 없으므로 시간대를 무시해야하므로 이것은 해킹입니다. 더 필요한 것이 있으면 moment.js를 사용합니다.

var d = new Date();    
d = new Date(d.getTime() - d.getTimezoneOffset() * 60000)
var yyyymmdd = t.toISOString().slice(0,0); 
// 2017-05-09T08:24:26.581Z (but this is not UTC)

The d.getTimezoneOffset() returns the time zone offset in minutes, and the d.getTime() is in ms, hence the x 60,000.


Here's what I've used in past projects:

var myDate = new Date();
var tzo = (myDate.getTimezoneOffset()/60)*(-1);
//get server date value here, the parseInvariant is from MS Ajax, you would need to do something similar on your own
myDate = new Date.parseInvariant('<%=DataCurrentDate%>', 'yyyyMMdd hh:mm:ss');
myDate.setHours(myDate.getHours() + tzo);
//here you would have to get a handle to your span / div to set.  again, I'm using MS Ajax's $get
var dateSpn = $get('dataDate');
dateSpn.innerHTML = myDate.localeFormat('F');

The .getTimezoneOffset() method reports the time-zone offset in minutes, counting "westwards" from the GMT/UTC timezone, resulting in an offset value that is negative to what one is commonly accustomed to. (Example, New York time would be reported to be +240 minutes or +4 hours)

To the get a normal time-zone offset in hours, you need to use:

var timeOffsetInHours = -(new Date()).getTimezoneOffset()/60

Important detail:
Note that daylight savings time is factored into the result - so what this method gives you is really the time offset - not the actual geographic time-zone offset.


With date from PHP code I used something like this..

function getLocalDate(php_date) {
  var dt = new Date(php_date);
  var minutes = dt.getTimezoneOffset();
  dt = new Date(dt.getTime() + minutes*60000);
  return dt;
}

We can call it like this

var localdateObj = getLocalDate('2015-09-25T02:57:46');

I mix the answers so far and add to it, because I had to read all of them and investigate additionally for a while to display a date time string from db in a user's local timezone format.

The datetime string comes from a python/django db in the format: 2016-12-05T15:12:24.215Z

Reliable detection of the browser language in JavaScript doesn't seem to work in all browsers (see JavaScript for detecting browser language preference), so I get the browser language from the server.

Python/Django: send request browser language as context parameter:

language = request.META.get('HTTP_ACCEPT_LANGUAGE')
return render(request, 'cssexy/index.html', { "language": language })

HTML: write it in a hidden input:

<input type="hidden" id="browserlanguage" value={{ language }}/>

JavaScript: get value of hidden input e.g. en-GB,en-US;q=0.8,en;q=0.6/ and then take the first language in the list only via replace and regular expression

const browserlanguage = document.getElementById("browserlanguage").value;
var defaultlang = browserlanguage.replace(/(\w{2}\-\w{2}),.*/, "$1");

JavaScript: convert to datetime and format it:

var options = { hour: "2-digit", minute: "2-digit" };
var dt = (new Date(str)).toLocaleDateString(defaultlang, options);

See: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString

The result is (browser language is en-gb): 05/12/2016, 14:58


The best solution I've come across is to create [time display="llll" datetime="UTC TIME" /] Tags, and use javascript (jquery) to parse and display it relative to the user's time.

http://momentjs.com/ Moment.js

will display the time nicely.


You could use the following, which reports the timezone offset from GMT in minutes:

new Date().getTimezoneOffset();

Note : - this function return a negative number.


// new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]])
var serverDate = new Date(2018, 5, 30, 19, 13, 15); // just any date that comes from server
var serverDateStr = serverDate.toLocaleString("en-US", {
  year: 'numeric',
  month: 'numeric',
  day: 'numeric',
  hour: 'numeric',
  minute: 'numeric',
  second: 'numeric'
})
var userDate = new Date(serverDateStr + " UTC");
var locale = window.navigator.userLanguage || window.navigator.language;

var clientDateStr = userDate.toLocaleString(locale, {
  year: 'numeric',
  month: 'numeric',
  day: 'numeric'
});

var clientDateTimeStr = userDate.toLocaleString(locale, {
  year: 'numeric',
  month: 'numeric',
  day: 'numeric',
  hour: 'numeric',
  minute: 'numeric',
  second: 'numeric'
});

console.log("Server UTC date: " + serverDateStr);
console.log("User's local date: " + clientDateStr);
console.log("User's local date&time: " + clientDateTimeStr);


getTimeZoneOffset() and toLocaleString are good for basic date work, but if you need real timezone support, look at mde's TimeZone.js.

There's a few more options discussed in the answer to this question


To convert date to local date use toLocaleDateString() method.

var date = (new Date(str)).toLocaleDateString(defaultlang, options);

To convert time to local time use toLocaleTimeString() method.

var time = (new Date(str)).toLocaleTimeString(defaultlang, options);

Don't know how to do locale, but javascript is a client side technology.

usersLocalTime = new Date();

will have the client's time and date in it (as reported by their browser, and by extension the computer they are sitting at). It should be trivial to include the server's time in the response and do some simple math to guess-timate offset.

참고URL : https://stackoverflow.com/questions/85116/display-date-time-in-users-locale-format-and-time-offset

반응형