UNPKG

3.17 kBJavaScriptView Raw
1
2/**
3 * @package BunnyJS
4 * @component BunnyDate
5 *
6 * Wrapper around native Date object
7 * Instead of new Date() use BunnyDate.create() which returns false for invalid dates
8 * Create Date from SQL or convert Date to SQL string
9 * Currently works only for Dates and not DateTimes
10 * Using local timezone
11 */
12export const BunnyDate = {
13
14 // Date object factories
15
16 /**
17 * Create Date object by year, month (1-12) and day
18 * Returns false if date is invalid, for example, February 31
19 *
20 * @param {Number|String} year - full year
21 * @param {Number|String} month - month number 1-12 or string including '07' etc.
22 * @param {Number|String} day - day number 1-31 or string including '07' etc.
23 *
24 * @returns {Date|boolean}
25 */
26 create(year, month, day) {
27 day = parseInt(day);
28 month = parseInt(month);
29 year = parseInt(year);
30 const date = new Date(year, month - 1, day);
31 if (date.getFullYear() === year && date.getMonth() === month - 1 && date.getDate() === day) {
32 return date
33 }
34 return false;
35 },
36
37 /**
38 * Creates Date object from SQL Date string, for example, '2016-07-14'
39 *
40 * @param {String} sqlDate
41 *
42 * @returns {Date|boolean}
43 */
44 createFromSql(sqlDate) {
45 const parts = sqlDate.split('-');
46 const year = parts[0];
47 const monthStr = parts[1];
48 const dayStr = parts[2];
49 return this.create(year, monthStr, dayStr);
50 },
51
52 /**
53 * Creates Date object from European Date string, for example, '14.07.2016'
54 *
55 * @param {String} euDate
56 *
57 * @returns {Date|boolean}
58 */
59 createFromEu(euDate) {
60 const parts = euDate.split('-');
61 const dayStr = parts[0];
62 const monthStr = parts[1];
63 const year = parts[2];
64 return this.create(year, monthStr, dayStr);
65 },
66
67 // Helpers
68
69 /**
70 * Get Date object meta object for custom methods and algorithms
71 *
72 * @param {Date} date
73 * @returns {Object}
74 */
75 getMeta(date) {
76 return {
77 year: date.getFullYear(),
78 monthIndex: date.getMonth(),
79 month: date.getMonth() + 1,
80 monthStr: this._twoDigits(date.getMonth() + 1),
81 day: date.getDate(),
82 dayStr: this._twoDigits(date.getDate())
83 }
84 },
85
86 // Date object to date string converters
87
88 /**
89 * Get SQL Date string from Date object (YYYY-MM-DD)
90 * @param {Date} date
91 * @returns {string}
92 */
93 toSqlDate(date) {
94 const meta = this.getMeta(date);
95 return meta.year + '-' + meta.monthStr + '-' + meta.dayStr;
96 },
97
98 /**
99 * Get European Date string from Date object (DD.MM.YYYY)
100 * @param {Date} date
101 * @returns {string}
102 */
103 toEuDate(date) {
104 const meta = this.getMeta(date);
105 return meta.dayStr + '.' + meta.monthStr + '.' + meta.year;
106 },
107
108 // private
109
110 _twoDigits(num) {
111 return (num < 10) ? '0' + num : num;
112 }
113
114};