I am trying to create two dynamic dates in html/javascript/jquery. I want the dates to be formatted like yyyy/mm/dd. The first date will return the last day of the previous month, and the second date will return the last day of the current month. Anyone know how to do this in the technologies listed above?
I am 99.9999% positive I can accomplish this by making a call 开发者_StackOverflow中文版to a backend page using C#, but I want to see if there is a more efficient way to do this right in the DOM (is DOM the correct terminology?).
From a previous question on SO, here is the code I am using now...
var d = new Date();
document.write(new Date(d.getFullYear(), d.getMonth() + 1, 0, 23, 59, 59));
It seems like you already have most of the answer:
var d = new Date();
var lastcurrent = new Date(d.getFullYear(), d.getMonth() + 1, 0, 23, 59, 59);
var lastprevious = new Date(d.getFullYear(), d.getMonth(), 0, 23, 59, 59);
Then to format them how you want you can use:
document.write(lastcurrent.getFullYear() + '/'
+ (lastcurrent.getMonth() + 1) + '/' + lastcurrent.getDate());
document.write(lastprevious.getFullYear() + '/'
+ (lastprevious.getMonth() + 1) + '/' + lastprevious.getDate());
jsFiddle here.
Edit
With two-digit month (last day should always be two digits):
document.write(lastcurrent.getFullYear()
+ '/' + String('00'+(lastcurrent.getMonth() + 1) ).slice(-2)
+ '/' + lastcurrent.getDate() );
document.write(lastprevious.getFullYear()
+ '/' + String('00'+ (lastprevious.getMonth() + 1) ).slice(-2)
+ '/' + lastprevious.getDate());
this should do it
var today = new Date();
var lastofpreviews = new Date( today.getUTCFullYear(), today.getUTCMonth() , 0 );
var lastofthis = new Date( today.getUTCFullYear(), today.getUTCMonth() + 1, 0 );
demo at http://jsfiddle.net/gaby/GW9B9/
var d = new Date();
document.write(new Date(d.getFullYear(), d.getMonth(), 0, 23, 59, 59).toLocaleFormat('%Y/%m/%d'));
document.write(new Date(d.getFullYear(), d.getMonth() + 1, 0, 23, 59, 59).toLocaleFormat('%Y/%m/%d'));
This will format the dates in the requested format (YYYY/mm/dd)
精彩评论