How to add 30 minutes to a JavaScript Date object?

前端 未结 20 3015
醉酒成梦
醉酒成梦 2020-11-21 23:21

I\'d like to get a Date object which is 30 minutes later than another Date object. How do I do it with JavaScript?

20条回答
  •  走了就别回头了
    2020-11-22 00:01

    For the lazy like myself:

    Kip's answer (from above) in coffeescript, using an "enum", and operating on the same object:

    Date.UNIT =
      YEAR: 0
      QUARTER: 1
      MONTH: 2
      WEEK: 3
      DAY: 4
      HOUR: 5
      MINUTE: 6
      SECOND: 7
    Date::add = (unit, quantity) ->
      switch unit
        when Date.UNIT.YEAR then @setFullYear(@getFullYear() + quantity)
        when Date.UNIT.QUARTER then @setMonth(@getMonth() + (3 * quantity))
        when Date.UNIT.MONTH then @setMonth(@getMonth() + quantity)
        when Date.UNIT.WEEK then @setDate(@getDate() + (7 * quantity))
        when Date.UNIT.DAY then @setDate(@getDate() + quantity)
        when Date.UNIT.HOUR then @setTime(@getTime() + (3600000 * quantity))
        when Date.UNIT.MINUTE then @setTime(@getTime() + (60000 * quantity))
        when Date.UNIT.SECOND then @setTime(@getTime() + (1000 * quantity))
        else throw new Error "Unrecognized unit provided"
      @ # for chaining
    

提交回复
热议问题