How do I convert a string to a UTC date?
I have the following text on my page:
<span class="UTCDate">Date.UTC(2011, 8, 7, 7, 9, 20)</span>
I'd like to do something like 开发者_运维百科this:
$(function () {
$('.UTCDate').each(function () {
var server_time_utc = $(this).html();
var subbed = new Date(server_time_utc - 12 * 60 * 60 * 1000);
var d = new Date(subbed + new Date().getTimezoneOffset());
var localTime = $.format.date(d, "ddd, MMMM dd GG hh:mma");
localTime = localTime.replace("GG", "at");
$(this).html(localTime);
});
});
I'm taking the UTC Date, changing it to the local browsers time and formatting it.
My problem is I get a string instead of a date object in this line:
var server_time_utc = $(this).html();
If I type:
var server_time_utc = Date.UTC(2011, 8, 7, 7, 9, 20);
I get a date object.
How can I make the text from $(this).html() return a date object instead of a string?
EDIT The string I get is
server_time_utc: "Date.UTC(2011, 8, 7, 7, 9, 20)"Accept a wider range of inputs
var matches = $(this).html().match(/\d+/g);
var date = new Date(Date.UTC.apply(this, matches));
This function will pull each number out of that string in order, then call Date.UTC with each number and return your Date object.
var server_time_utc = Date.parse($(this).html());
精彩评论