[javascript] JavaScript에서 시간대 이름을 어떻게 얻을 수 있습니까?

시간대 오프셋을 얻는 방법을 알고 있지만 필요한 것은 “America / New York”과 같은 것을 감지하는 기능입니다. JavaScript에서도 가능합니까 아니면 오프셋을 기반으로 게스트 화해야 할 것입니까?



답변

국제화 API의 지원은 사용자의 시간대를 받고되며, 지원되는 모든 현재 브라우저에서.

console.log(Intl.DateTimeFormat().resolvedOptions().timeZone)

Internationalization API를 지원하는 일부 이전 브라우저 버전에서는 timeZone속성이 undefined사용자의 시간대 문자열이 아닌 로 설정됩니다 . 내가 알 수있는 한, 작성 당시 (2017 년 7 월) IE11제외한 모든 현재 브라우저 는 사용자 시간대를 문자열로 반환합니다.


답변

대부분의 찬성 답변 은 아마도 시간대를 얻는 가장 좋은 방법 일 것입니다.Intl.DateTimeFormat().resolvedOptions().timeZone 정의에 따라 영어로 된 IANA 시간대 이름을 반환합니다.

현재 사용자의 언어로 시간대 이름을 원하면 다음 Date과 같이의 문자열 표현 에서 구문 분석 할 수 있습니다 .

function getTimezoneName() {
  const today = new Date();
  const short = today.toLocaleDateString(undefined);
  const full = today.toLocaleDateString(undefined, { timeZoneName: 'long' });

  // Trying to remove date from the string in a locale-agnostic way
  const shortIndex = full.indexOf(short);
  if (shortIndex >= 0) {
    const trimmed = full.substring(0, shortIndex) + full.substring(shortIndex + short.length);

    // by this time `trimmed` should be the timezone's name with some punctuation -
    // trim it from both sides
    return trimmed.replace(/^[\s,.\-:;]+|[\s,.\-:;]+$/g, '');

  } else {
    // in some magic case when short representation of date is not present in the long one, just return the long one as a fallback, since it should contain the timezone's name
    return full;
  }
}

console.log(getTimezoneName());

Chrome 및 Firefox에서 테스트되었습니다.

물론 일부 환경에서는 의도 한대로 작동하지 않습니다. 예를 들어 node.js는 GMT+07:00이름 대신 GMT 오프셋 (예 :)을 반환합니다 . 하지만 여전히 대체로 읽을 수 있다고 생각합니다.

PS는 Intl...솔루션 과 마찬가지로 IE11에서 작동하지 않습니다 .


답변

이 스크립트를 사용할 수 있습니다.
http://pellepim.bitbucket.org/jstz/

여기에 저장소를 포크하거나 복제하십시오.
https://bitbucket.org/pellepim/jstimezonedetect

스크립트를 포함하면- jstz.olson.timezones변수 에 시간대 목록을 가져올 수 있습니다 .

그리고 다음 코드는 클라이언트 브라우저의 시간대를 결정하는 데 사용됩니다.

var tz = jstz.determine();
tz.name();

jstz를 즐기십시오!


답변

이름으로 시간대 검색 (예 : “미국 / 뉴욕”)

moment.tz.guess();


답변

http://www.timeanddate.com/time/zones/ 에서 매핑 테이블을 사용하여 자신 만의 코드를 작성할 수 있습니다
.

또는 moment-timezone 라이브러리 사용 :
http://momentjs.com/timezone/docs/

보다 zone.name; // America/Los_Angeles

또는이 라이브러리 :
https://github.com/Canop/tzdetect.js


답변

이것은 GMT이전 자바 스크립트에서 시간대 코드 (예 :)를 가져옵니다 ( 예전 엔진에서 Google 앱 스크립트를 사용하고 있습니다).

function getTimezoneName() {
  return new Date().toString().get(/\((.+)\)/);
}

누군가 필요한 경우를 대비하여 여기에 넣는 것입니다.


답변

이 코드는 여기 에서 참조 하십시오.

<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js">
</script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jstimezonedetect/1.0.4/jstz.min.js">
</script>
<script type="text/javascript">
  $(document).ready(function(){
    var tz = jstz.determine(); // Determines the time zone of the browser client
    var timezone = tz.name(); //'Asia/Kolhata' for Indian Time.

    alert(timezone);
});
</script>