How to display localized date and time information to web users with ASP.NET

孤街醉人 提交于 2019-12-03 13:09:27

You should pass the time string to the client in a standard form, such as ISO8601:

var timeString = '2012-01-02T16:00:00Z';

Some browsers will correctly parse ISO8601 strings and some wont, so parse it manually to be sure. That is pretty simple—create a local date object then set the UTC date and time:

function localDateFromUTC(s) {

  var x = s.split(/[-\s:tz]/i);
  var d = new Date();

  d.setUTCFullYear(x[0], x[1], x[2]);
  d.setUTCHours(x[3], x[4], x[5]);
  return d;
}

var s = '2012-01-02T16:00:00Z';
var d = localDateFromUTC(s);
alert(d); // Shows local date and time for the provided UTC date and time

If you want a specific output, you need to format it manually, e.g.

function formatDate(d) {
  var days = ['Sunday','Monday','Tuesday','Wednesday',
              'Thursday','Friday','Saturday'];
  var months = ['January','February','March','April','May','June','July',
                'August','September','October','November','December'];

  return days[d.getDay()] + ', ' + d.getDate() + ' ' + 
              months[d.getMonth()] + ', ' + d.getFullYear();
} 

You can try using toLocaleString() but results vary greatly across browsers, most seem to ignore local settings anyway.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!