-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
index.js
59 lines (52 loc) · 2.19 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import toDate from '../toDate/index.js'
import toInteger from '../_lib/toInteger/index.js'
import setMonth from '../setMonth/index.js'
/**
* @name set
* @category Common Helpers
* @summary Set the object to a given date
*
* @description
* Set the object to a given date
*
* @param {Date|Number} date - the date to be changed
* @param {Object} [options] - an object with options
* @param {Number} [options.years=0] - the number of years to be set
* @param {Number} [options.months=0] - the number of months to be set
* @param {Number} [options.days=0] - the number of days to be set
* @param {Number} [options.hours=0] - the number of hours to be set
* @param {Number} [options.minutes=0] - the number of minutes to be set
* @param {Number} [options.seconds=0] - the number of seconds to be set
* @param {Number} [options.milliseconds=0] - the number of milliseconds to be set
* @returns {Date} the new date with options set
* @throws {TypeError} 2 arguments required
*/
export default function set(dirtyDate, dirtyOptions) {
if (arguments.length < 2) {
throw new TypeError(
'2 arguments required, but only ' + arguments.length + ' present'
)
}
var options = dirtyOptions || {}
var years = options.years == null ? 0 : toInteger(options.years)
var months = options.months == null ? 0 : toInteger(options.months)
var days = options.days == null ? 0 : toInteger(options.days)
var hours = options.hours == null ? 0 : toInteger(options.hours)
var minutes = options.minutes == null ? 0 : toInteger(options.minutes)
var seconds = options.seconds == null ? 0 : toInteger(options.seconds)
var milliseconds =
options.milliseconds == null ? 0 : toInteger(options.milliseconds)
var date = toDate(dirtyDate)
// Check if date is Invalid Date because Date.prototype.setFullYear ignores the value of Invalid Date
if (isNaN(date)) {
return new Date(NaN)
}
if (years > 0) date.setFullYear(years)
if (months > 0) date = setMonth(date, months)
if (days > 0) date.setDate(days)
if (hours > 0) date.setHours(hours)
if (minutes > 0) date.setMinutes(minutes)
if (seconds > 0) date.setSeconds(seconds)
if (milliseconds > 0) date.setMilliseconds(milliseconds)
return date
}