0

我有一个将 SQL 日期时间戳转换为格式化时间的函数。它在 iOS 设备上看起来不错,但在 Android 设备上显示为军用时间。我怎样才能让它在 android 设备上返回 toLocaleTimeString() 而不是军事时间?

function fromDateString(str) {
    var res = str.match(/\/Date\((\d+)(?:([+-])(\d\d)(\d\d))?\)\//);
    if (res == null)
        return new Date(NaN); // or something that indicates it was not a DateString
    var time = parseInt(res[1], 10);
    if (res[2] && res[3] && res[4]) {
        var dir = res[2] == "+" ? -1 : 1,
            h = parseInt(res[3], 10),
            m = parseInt(res[4], 10);
        time += dir * (h*60+m) * 60000;
    }
    return formatdate.toLocaleTimeString();
}
4

1 回答 1

6

Date.toLocaleTimeString()函数是“依赖于实现的”,这意味着如果您想在所有设备上保证某种格式,那么您必须自己应用它。

这是我的做法:

function formatTimeString(date) {
  if ((typeof(date)!=='object') || (date.constructor!==Date)) {
    throw new Error('argument must be a Date object');
  }
  function pad(s) { return ((''+s).length < 2 ? '0' : '') + s; }
  function fixHour(h) { return (h==0?'12':(h>12?h-12:h)); }
  var h=date.getHours(), m=date.getMinutes(), s=date.getSeconds()
    , timeStr=[pad(fixHour(h)), pad(m), pad(s)].join(':');
  return timeStr + ' ' + (h < 12 ? 'AM' : 'PM');
}

formatTimeString(new Date());
// => "09:19:03 AM"
formatTimeString(new Date('2012-12-19T20:09:10-0700'));
// => "08:09:10 PM"
formatTimeString(new Date('2012-12-19T00:13:14-0700'));
// => "12:13:14 AM"
于 2012-12-19T16:12:25.560 回答