假设您想要字符串而不是 Epoch 等的毫秒或秒数(您尚未指定),请参阅Date
Javascript
var today = new Date();
/*
i) When the user clicks on View Last Week , I need to get the start date and end date. i.e.
end date : current date at his local time when he clicked on 'View last week'.
start date : if it is 'View last week', the start date is the date of the 1 st day of the 7 days.
*/
console.log({
start: new Date(today.getTime() - 7 * 24 * 60 * 60 * 1000).toString(),
end: today.toString()
});
/*
ii) Similarly as above for 'View last month' except that the start date is the date of the the first day of the 30 days.
*/
console.log({
start: new Date(today.getTime() - 30 * 24 * 60 * 60 * 1000).toString(),
end: today.toString()
});
/*
iii) For 'View 90 days', the start date should be the date of the first day of the 90 days.
*/
console.log({
start: new Date(today.getTime() - 90 * 24 * 60 * 60 * 1000).toString(),
end: today.toString()
});
/*
Current time zone and convert to GMT: his current local time zone when he clicked on 'View last week','View last month','View 90 days' which is converted to GMT timezone.
In Javascript,I need to calculate these dates and the GMT timezone based on his local time and send it to my service .
*/
function plz(number, length) {
var output = number.toString();
while (output.length < length) {
output = "0" + output;
}
return output;
}
var dayName = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
monthName = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
console.log({
today_local: today.toString(),
today_utc: dayName[today.getUTCDay()] + " " + monthName[today.getUTCMonth()] + " " + today.getUTCDate() + " " + today.getUTCFullYear() + " " + plz(today.getUTCHours(), 2) + ":" + plz(today.getUTCMinutes(), 2) + ":" + plz(today.getUTCSeconds(), 2) + " GMT"
});
/*
or if a custom format not required, can use RFC-1123 formatted date stamp
*/
console.log({
today_local: today.toString(),
today_utc: today.toUTCString()
});
输出
Object {start: "Fri Oct 11 2013 15:21:34 GMT+0200 (CEST)", end: "Fri Oct 18 2013 15:21:34 GMT+0200 (CEST)"}
Object {start: "Wed Sep 18 2013 15:21:34 GMT+0200 (CEST)", end: "Fri Oct 18 2013 15:21:34 GMT+0200 (CEST)"}
Object {start: "Sat Jul 20 2013 15:21:34 GMT+0200 (CEST)", end: "Fri Oct 18 2013 15:21:34 GMT+0200 (CEST)"}
Object {today_local: "Fri Oct 18 2013 15:21:34 GMT+0200 (CEST)", today_utc: "Fri Oct 18 2013 13:21:34 GMT"}
Object {today_local: "Fri Oct 18 2013 15:29:59 GMT+0200 (CEST)", today_utc: "Fri, 18 Oct 2013 13:29:59 GMT"}
jsFiddle