如何获取用户时区的完整时间和日期

时间:2019-01-30 17:25:56

标签: javascript

我正在尝试使用原始Javascript显示日期和时间。我想显示用户所在时区的完整日期和时间。

这是我想要的输出:

Wednesday, January 30th 2019 at 08:48:47 AM PST

这是我到目前为止的内容:

var date = new Date();
var n = date.toDateString();
var time = date.toLocaleTimeString();

document.getElementById('time').innerHTML = n + ' at ' + time;
<div id="time"></div>

所以我很接近。我现在需要做的就是将日期和月份名称扩展为全名,在日期中添加st / rd / th并将用户的时区附加到末尾。

3 个答案:

答案 0 :(得分:1)

香草JS - 没问题!国际化API抢救! (摘自MDN

var date = new Date(), 
    locale = 'en-US',
    timeZone = 'America/Los_Angeles';

var weekday = new Intl.DateTimeFormat(locale, { weekday: 'long', timeZone }).format(date);
var month = new Intl.DateTimeFormat(locale, { month: 'long', timeZone }).format(date);
var day = new Intl.DateTimeFormat(locale, { day: '2-digit', timeZone }).format(date);

var time = new Intl.DateTimeFormat(locale, 
{
  hour: '2-digit', 
  minute: '2-digit', 
  second: '2-digit',
  hour12: true,
  timeZone

}).format(date);

console.log(`${weekday}, ${month} ${day}th ${date.getFullYear()} at ${time}`);

答案 1 :(得分:1)

var date = new Date();
var n = date.toDateString();
var time = date.toLocaleTimeString();
var hours = date.getHours();
var AP = hours >= 12 ? 'PM' : 'AM';

var day = date.getDay();
var weekday = "";
if(day === 0)weekday = "Monday"; else if(day === 1) weekday = "Tuesday" ; 
else if(day === 2) weekday = "Wednesday";  else if(day === 3) weekday = "Thursday";
else if(day === 4) weekday = "Friday"; else if(day === 5) weekday = "Saturday";
else if(day === 6) weekday = "Sunday";

var monthNo = date.getMonth();
var month = "";
if(monthNo === 0)month = "January";
else if(monthNo === 1)month = "February";
else if(monthNo === 2)month = "March";
else if(monthNo === 3)month = "April";
else if(monthNo === 4)month = "May";
else if(monthNo === 5)month = "June";
else if(monthNo === 6)month = "July";
else if(monthNo === 7)month = "August";
else if(monthNo === 8)month = "September";
else if(monthNo === 9)month = "October";
else if(monthNo === 10)month = "November";
else if(monthNo === 11)month = "December";

var dateNo = date.getDate();
var dateletter = "";

if (dateNo > 3 && dateNo < 21) dateletter =  "th"; 
else if(dateNo % 10 === 1) dateletter =  "st"; 
else if(dateNo % 10 === 2) dateletter =  "nd"; 
else if(dateNo % 10 === 3) dateletter =  "rd"; 
else dateletter = "th";


console.log(weekday +", " + month + " " + dateNo + dateletter + " at " + time + " " + 
" " +AP);`

要为此添加时区,可以使用javascript gettimeoffset()方法获取时区偏移量。根据该信息,您可以确定时区。

答案 2 :(得分:1)

此解决方案使用Intl.DateTimeFormat(),因此我们可以利用FormatToParts()函数,然后应用自定义map(),最后是reduce(),以获得所需的输出。

map()函数中,我们将日期后缀附加到输出'st','nd','rd'和'th'。例如。 1、2、3、4。后缀附加到日期本身,而不是相应的literal键,因为我们需要知道日期的值,因此这是最简单的方法。

我们确实替换literal的值时,主要是为了删除多余的逗号(默认情况下为逗号),并且还要在时间之前显示at

在MDN上的引用:

const d = new Date();

const formatOptions = {
    weekday: 'long', month: 'long', day: 'numeric', hour: 'numeric',
    minute: 'numeric', year: 'numeric', timeZoneName: 'short', hour12: true
};

// Using Intl.DateTimeFormat so we have access to
//     formatToParts function which produces
//     an Array of objects containing the formatted date in parts
const dateFormat = new Intl.DateTimeFormat(undefined, formatOptions);

// Keep track of 'literal' key counts (`literal` is the separator)
let separatorIndex = 0;

// Where the magic happens using map() and reduce()
const dateString = dateFormat.formatToParts(d).map(({type, value}) => {
  switch (type) {
    case 'literal' :
      separatorIndex++;
      
      switch (separatorIndex) {
        case 3 : // Day separator
          return ' ';
          break;
        case 4 : // Year separator
          return ' at ';
        default: return value;          
      }
      break;
    case 'day' :
      // Append appropriate suffix
      switch (value) {
        case (value.slice(-1) === 1) :
          return value.concat('st');
          break;
        case (value.slice(-1) === 2) :
          return value.concat('nd');
          break;
        case (value.slice(-1) === 3) :
          return value.concat('rd');
          break;
        default: return value.concat('th');
      }
      break;
    case 'hour' :
      // Prepend 0 when less than 10 o'clock
      return (value < 10) ? '0'.concat(value) : value;
      break;
    default: return value;
  }
}).reduce((string, part) => {
  return string.concat(part)
});

// Not part of answer; only for output result
document.write(dateString);