I'd like to get a Date object which is 30 minutes later than another Date object. How do I do it with JavaScript?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- Can php detect if javascript is on or not?
For the lazy like myself:
Kip's answer (from above) in coffeescript, using an "enum", and operating on the same object:
Using a Library
If you are doing a lot of date work, you may want to look into JavaScript date libraries like Datejs or Moment.js. For example, with Moment.js, this is simply:
Vanilla Javascript
This is like chaos's answer, but in one line:
Where
diff
is the difference in minutes you want fromoldDateObj
's time. It can even be negative.Or as a reusable function, if you need to do this in multiple places:
Be Careful with Vanilla Javascript. Dates Are Hard!
You may think you can add 24 hours to a date to get tomorrow's date, right? Wrong!
It turns out, if the user observes daylight saving time, a day is not necessarily 24 hours long. There is one day a year that is only 23 hours long, and one day a year that is 25 hours long. For example, in most of the United States and Canada, 24 hours after midnight, Nov 2, 2014, is still Nov 2:
This is why using one of the afore-mentioned libraries is a safer bet if you have to do a lot of work with this.
Below is a more generic version of this function that I wrote. I'd still recommend using a library, but that may be overkill/impossible for your project. The syntax is modeled after MySQL DATE_ADD function.
Working jsFiddle demo.
This is what I do which seems to work quite well:
Then you can just call this like this:
I always create 7 functions, to work with date in JS: addSeconds, addMinutes, addHours, addDays, addWeeks, addMonths, addYears.
You can see an example here: http://jsfiddle.net/tiagoajacobi/YHA8x/
How to use:
This are the functions: