Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
302 views
in Technique[技术] by (71.8m points)

javascript - How to get 30 days prior to current date?

I have a start calendar input box and an end calendar input box. We want defaults start calendar input box 30 days prior to current date and the end calendar input box to be the current date. Here is my date vars.

var today = new Date(),
    dd    = today.getDate(),
    mm    = today.getMonth(),
    yyyy  = today.getFullYear(),
    month = ["January", "February", "March",
        "April", "May", "June", "July", "August",
        "September", "October" "November", "December"],
    startdate = month[mm] + ", " + yyyy.toString();

The end date would be something like var enddate = startdate - 30; Obviously this won't work.

So if the current date is December 30, 2011 I'd want the start date to read December 1, 2011.

EDIT: My question was answered... sort of. Date.today(); and Date.today().add(-30); work but I need the date in the format of January 13, 2012. Not Fri Jan 13 2012 10:48:56 GMT -055 (EST). Any help?

MORE EDIT: As of this writing it's 2018. Just use Moment.js. It's the best.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try this

var today = new Date()
var priorDate = new Date().setDate(today.getDate()-30)

As noted by @Neel, this method returns in Javascript Timestamp format. To convert it back to date object, you need to pass the above to a new Date object; new Date(priorDate).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...