UNPKG

11.4 kBMarkdownView Raw
1# node-datetime
2
3©Nobuyori Takahashi < <voltrue2@yahoo.com> >
4
5An extended Date object for javascript.
6
71. Handles offests by days and hours.
8
92. Built-in formatting function.
10
113. Time based value calculation.
12
13## Installation
14
15# Installation via npm
16
17`npm node-datetime`
18
19# Use node-datetime in browser
20
21In order to use `node-datetime` in browser, you will need to load the script as shown below:
22
23The browser script file is located at: `node-datetime/release/browser/node_datetime.js`.
24
25## Add the script to your HTML
26
27The "src" path must be according to your server setup.
28
29```html
30<script type="text/javascript" src="./node_datetime.js"></script>
31```
32
33## window.DateTime
34
35When you add the script to your HTML page correctly, `window.DateTime` object will be accessible as a global object.
36
37The object is the equivalent of `var datetime = require('node-datetime');` in node.js version.
38
39***
40
41# Backward Compatibilty Break Warning
42
43From version `1.0.0`, certain APIs have changed their behavior.
44
45### .now()
46
47This API used to return a fixed timestamp in milliseconds meaning that it was returning the timestamp of the instance of `datetime`.
48
49Now `.now()` returns a calculated current timestamp in milliseconds with time offset if given.
50
51**Example**:
52
53You could get current time of the past, for exmaple.
54
55```javascript
56var datetime = require('node-datetime');
57var past = '2015-01-01 00:00:00';
58var pastDateTime = datetime.create(past);
59// get the current timestamp of the past
60setTimeout(function () {
61 var pastNow = pastDateTime.now();
62 // this would be 1420038010000
63 console.log(pastNow);
64 // this would be 2015-01-01 00:00:10
65 console.log(new Date(1420038010000));
66}, 1000);
67```
68
69### .getTime()
70
71This API is the same as former `.now()`. It returns the timestamp of `datetime` object.
72
73**Example**:
74
75
76```javascript
77var datetime = require('node-datetime');
78var past = '2015-01-01 00:00:00';
79var pastDateTime = datetime.create(past);
80// get the current timestamp of the past
81setTimeout(function () {
82 var pastTime = pastDateTime.getTime();
83 // this would be 1420038000000
84 console.log(pastNow);
85 // this would be 2015-01-01 00:00:00
86 console.log(new Date(1420038000000));
87}, 1000);
88```
89
90## API
91
92### .setPeriod(periodNames [array])
93
94Replaces the default period names (AM and PM).
95
96```
97datetime.setPeriod([ 'Ante Meridiem', 'Post Meridiem' ]);
98```
99
100### .setWeekNames(listOfWeekNames [array])
101
102Replaces the default week names with custom names.
103
104**NOTE** you may have nulls in your custom week name array to keep some of the default names:
105
106```
107datetime.setWeekNames([
108 'My Custom Monday',
109 // keep the default name
110 null,
111 ...
112]);
113```
114
115### .setShortWeekNames(listOfShortWeekNames [array])
116
117**NOTE** you may have nulls in your custom name array to keep some of the default names:
118
119```
120datetime.setShortWeekNames([
121 'My Custom Name',
122 // keep the default name
123 null,
124 ...
125]);
126```
127
128### .setMonthNames(listOfMonthNames [array])
129
130**NOTE** you may have nulls in your custom name array to keep some of the default names:
131
132```
133datetime.setMonthNames([
134 'My Custom Name',
135 // keep the default name
136 null,
137 ...
138]);
139```
140
141### .setShortMonthNames(listOfShortMonthNames [array])
142
143**NOTE** you may have nulls in your custom name array to keep some of the default names:
144
145```
146datetime.setShortMonthNames([
147 'My Custom Name',
148 // keep the default name
149 null,
150 ...
151]);
152```
153
154#### .create(time [*mix], defaultFormat [*string])
155
156Returns an instance of DateTime object.
157
158`time` can be a `YYYY-MM-DD HH:MM:SS` style string, javascript Date object, or timestamp such as `Date.now()`.
159
160Example:
161
162```javascript
163var datetime = require('node-datetime');
164var dt = datetime.create();
165var formatted = dt.format('m/d/Y H:M:S');
166// e.g. 04/28/2015 21:13:09
167```
168
169#### .setOffsetInDays(offsetDays [number])
170
171Sets a shared offset in days.
172
173If this is set, all instances of DateTime object will have the given offset in days.
174
175This can be individually overridden.
176
177#### .setOffsetInHourss(offsetHours [number])
178
179Sets a shared offset in hours.
180
181If this is set, all instances of DateTime object will have the given offset in hours.
182
183This can be individually overridden.
184
185#### .setDefaultFormat(defaultFormat [string])
186
187Sets a shared default format.
188
189If this is set, all instances of DateTime object will have the given format as default.
190
191This can be individually overridden.
192
193## DateTime Object
194
195### Methods
196
197#### .format(format [*string])
198
199Returns a formatted date time string.
200
201If default format is set and the format string is not passed to `.format()`, default format will be used.
202
203Example With Format:
204
205```javascript
206var datetime = require('node-datetime');
207var dt = datetime.create('2015-04-30 09:52:00');
208var formattedDate = dt.format('m/d/y H:M');
209console.log(formattedDate);
210// 04/30/15 09:52
211```
212
213Example With Default Format:
214
215```javascript
216var datetime = require('node-datetime');
217var dt = datetime.create('2015-04-30 14:30:00', 'Y/m/d H:I');
218var formattedDate = dt.format();
219console.log(formattedDate);
220// 2015/04/30 02:30
221```
222
223#### Formatting rules
224
225|Format|Meaning|
226|---|---|
227|y|The last 2 digit of the year|
228|Y|Year|
229|m|Month with leading 0|
230|n|Shortened name of a month|
231|f|Full name of a month|
232|d|Date with leading 0|
233|H|Hours with leading 0 in 24 hours format|
234|I|Hours with leading 0 in 12 hours format|
235|M|Minutes with leading 0|
236|S|Seconds with leading 0|
237|N|Milliseconds with leading 0|
238|p|Period (AM or PM)|
239
240#### .offsetInDays(offset [number])
241
242Offests the date.
243
244**NOTE**: By giving more than 30 days or 365 days, it can exceed current year or month.
245
246Example:
247
248```javascripript
249var datetime = require('node-datetime');
250var dt = datetime.create();
251// 1 day in the future
252dt.offsetInDays(1);
253```
254
255```javascripript
256var datetime = require('node-datetime');
257var dt = datetime.create();
258// 1 day in the past
259dt.offsetInDays(-1);
260```
261
262#### .offsetInHours(offset [number])
263
264Offests the hours.
265
266**NOTE**: By giving more than 24 hours, it can exceed current date and so on.
267
268Example:
269
270```javascripript
271var datetime = require('node-datetime');
272var dt = datetime.create();
273// 1 hour in the future
274dt.offsetInHours(1);
275```
276
277```javascripript
278var datetime = require('node-datetime');
279var dt = datetime.create();
280// 1 hour in the past
281dt.offsetInHours(-1);
282```
283
284#### .now()
285
286Returns a unix timestamp in milliseconds.
287
288**NOTE:** The method automatically calculates the offset time.
289
290#### .getTime()
291
292Returns a fixed unix timestamp in milliseconds.
293
294#### .epoch()
295
296Returns a fixed unix timestamp in seconds.
297
298#### .getDatesInRange(date [mix])
299
300Returns an array of DateTime objects within the given range in days.
301
302**NOTE**: `date` can be either DateTime or Date.
303
304Example:
305
306```javascript
307var datetime = require('node-datetime');
308var dt = datetime.create('2015-01-01');
309var dates = dt.getDatesInRange(datetime.create('2015-01-10'));
310// dates = [ ... ];
311// dates will contain instances of DateTime object from 2015-01-01 to 2015-01-10
312````
313
314#### .geHoursInRange(date [mix])
315
316Returns an array of DateTime objects within the given range in hours.
317
318**NOTE**: `date` can be either DateTime or Date.
319
320Example:
321
322```javascript
323var datetime = require('node-datetime');
324var dt = datetime.create('2015-01-01 00:00:00');
325var dates = dt.getDatesInRange(datetime.create('2015-01-02 00:00:00'));
326// dates = [ ... ];
327// dates will contain instances of DateTime object from 2015-01-01 00:00:00 to 2015-01-02 00:00:00
328````
329
330#### .createTimedNumber(conf [object])
331
332Returns an instance of TimedNumber that changes its value over time.
333
334conf:
335
336```javascript
337{
338 "max": 10, // maximum value
339 "min": 0, // minimum value
340 "interval": 60000, // value increments/decrements every "interval"
341 "step": 1, // at every interval, the value increments/decrements by "step"
342 "type": "inc", // either "inc" for incrementing type of "dec" for decrementing type
343 "init": 10 // initial value to start with
344 "lastUpdate": null // an optional time stamp to control the last update state
345}
346```
347
348Usage Example:
349
350TimedNumber that recovers its value by 1 every 1 second.
351
352```javascript
353var datetime = require('node-datetime');
354var config = {
355 max: 10,
356 min: 0,
357 interval: 1000,
358 step: 1,
359 type: 'inc',
360 init: 0
361};
362var td = datetime.createTimedNumber(config);
363setTimeout(function () {
364 var value = td.getValue();
365 // value should be 1
366}, 1000);
367```
368
369```javascript
370var datetime = require('node-datetime');
371var config = {
372 max: 10,
373 min: 0,
374 interval: 1000,
375 step: 1,
376 type: 'inc',
377 init: 10
378};
379var td = datetime.createTimedNumber(config);
380td.dec(5);
381setTimeout(function () {
382 var value = td.getValue();
383 // value should be 6
384}, 1000);
385```
386
387### TimedNumber Class
388
389#### .getValue()
390
391Returns the current value.
392
393#### .inc(incrementValue [number])
394
395Increments the current value by incrementValue.
396
397Returns `true` if successful.
398
399#### .dec(decrementValue [number])
400
401Decrements the current value by decrementValue.
402
403Returns `true` if successful.
404
405#### .reset()
406
407Resets the state of `TimedNumber` object to its initial state.
408
409#### .getMaxValue()
410
411Returns maximum value.
412
413#### .getMinValue()
414
415Returns minimum value.
416
417#### .getInterval()
418
419Returns the interval for every update in milliseconds.
420
421#### .getStep()
422
423Returns the value of step for every update.
424
425#### .toObject()
426
427Returns a JSON format of `TimedNumber` object.
428
429You can reconstruct exact same timed number object from this JSON object.
430
431Example:
432
433```javascript
434var datetime = require('node-datetime');
435var config = {
436 max: 10,
437 min: 0,
438 interval: 1000,
439 step: 1,
440 type: 'inc',
441 init: 10
442};
443var timedNumber = datetime.createTimedNumber(conf);
444// do things
445timedNumber.dec(3);
446// store it in database as JSON
447var json = timedNumber.toOjbect();
448// read json back from the database and reconstruct timed number object
449var timedNumber2 = datetime.createTimedNumber(json);
450// timedNumber2 will have the same state as timedNumber
451```
452
453### .createTimedState(conf)
454
455Returns an instance of TimedState object that changes its state over time.
456
457conf:
458
459```
460{
461 states: [ 'A', 'B', 'C' ... ] // an array of states to represent the order of states
462 interval: 1000 // interval in milliseconds for the state to change
463 init: 0 // initial position of the states array
464 loop: false // if true, the states will loop
465}
466```
467
468Example:
469
470```javascript
471var datetime = require('node-datetime');
472var conf = {
473 states: [ 'one', 'two', 'three' ],
474 interval: 1000,
475 init: 0,
476 loop: false
477};
478// create the TimedState object that changes its state every 1 second from 'one' and it stops at 'three'
479var ts = datetime.createTimedState(conf);
480```
481
482### TimedState Class
483
484#### .getState()
485
486Returns the current state.
487
488#### .forward(position [*number])
489
490Forces the state to move forward by the given number. If no position is given, it will move forward by one.
491
492#### .backward(position [*number])
493
494Forces the state to move backward by the given number, If no position is given, it will move backward by one.
495
496#### .getStates()
497
498Returns the state array.
499
500#### .getInterval()
501
502Returns the interval in milliseconds
503
504#### .reset()
505
506Resets the state to its initial state.
507
508#### .toObject()
509
510Returns a JSON format of `TimedState` object.
511
512You can reconstruct exact same timed number object from this JSON object.
513