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|w|Shortened name of the week day|
240|W|Full name of the week day|
241
242#### .offsetInDays(offset [number])
243
244Offests the date.
245
246**NOTE**: By giving more than 30 days or 365 days, it can exceed current year or month.
247
248Example:
249
250```javascripript
251var datetime = require('node-datetime');
252var dt = datetime.create();
253// 1 day in the future
254dt.offsetInDays(1);
255```
256
257```javascripript
258var datetime = require('node-datetime');
259var dt = datetime.create();
260// 1 day in the past
261dt.offsetInDays(-1);
262```
263
264#### .offsetInHours(offset [number])
265
266Offests the hours.
267
268**NOTE**: By giving more than 24 hours, it can exceed current date and so on.
269
270Example:
271
272```javascripript
273var datetime = require('node-datetime');
274var dt = datetime.create();
275// 1 hour in the future
276dt.offsetInHours(1);
277```
278
279```javascripript
280var datetime = require('node-datetime');
281var dt = datetime.create();
282// 1 hour in the past
283dt.offsetInHours(-1);
284```
285
286#### .now()
287
288Returns a unix timestamp in milliseconds.
289
290**NOTE:** The method automatically calculates the offset time.
291
292#### .getTime()
293
294Returns a fixed unix timestamp in milliseconds.
295
296#### .epoch()
297
298Returns a fixed unix timestamp in seconds.
299
300#### .getDatesInRange(date [mix])
301
302Returns an array of DateTime objects within the given range in days.
303
304**NOTE**: `date` can be either DateTime or Date.
305
306Example:
307
308```javascript
309var datetime = require('node-datetime');
310var dt = datetime.create('2015-01-01');
311var dates = dt.getDatesInRange(datetime.create('2015-01-10'));
312// dates = [ ... ];
313// dates will contain instances of DateTime object from 2015-01-01 to 2015-01-10
314````
315
316#### .geHoursInRange(date [mix])
317
318Returns an array of DateTime objects within the given range in hours.
319
320**NOTE**: `date` can be either DateTime or Date.
321
322Example:
323
324```javascript
325var datetime = require('node-datetime');
326var dt = datetime.create('2015-01-01 00:00:00');
327var dates = dt.getDatesInRange(datetime.create('2015-01-02 00:00:00'));
328// dates = [ ... ];
329// dates will contain instances of DateTime object from 2015-01-01 00:00:00 to 2015-01-02 00:00:00
330````
331
332#### .createTimedNumber(conf [object])
333
334Returns an instance of TimedNumber that changes its value over time.
335
336conf:
337
338```javascript
339{
340 "max": 10, // maximum value
341 "min": 0, // minimum value
342 "interval": 60000, // value increments/decrements every "interval"
343 "step": 1, // at every interval, the value increments/decrements by "step"
344 "type": "inc", // either "inc" for incrementing type of "dec" for decrementing type
345 "init": 10 // initial value to start with
346 "lastUpdate": null // an optional time stamp to control the last update state
347}
348```
349
350Usage Example:
351
352TimedNumber that recovers its value by 1 every 1 second.
353
354```javascript
355var datetime = require('node-datetime');
356var config = {
357 max: 10,
358 min: 0,
359 interval: 1000,
360 step: 1,
361 type: 'inc',
362 init: 0
363};
364var td = datetime.createTimedNumber(config);
365setTimeout(function () {
366 var value = td.getValue();
367 // value should be 1
368}, 1000);
369```
370
371```javascript
372var datetime = require('node-datetime');
373var config = {
374 max: 10,
375 min: 0,
376 interval: 1000,
377 step: 1,
378 type: 'inc',
379 init: 10
380};
381var td = datetime.createTimedNumber(config);
382td.dec(5);
383setTimeout(function () {
384 var value = td.getValue();
385 // value should be 6
386}, 1000);
387```
388
389### TimedNumber Class
390
391#### .getValue()
392
393Returns the current value.
394
395#### .inc(incrementValue [number])
396
397Increments the current value by incrementValue.
398
399Returns `true` if successful.
400
401#### .dec(decrementValue [number])
402
403Decrements the current value by decrementValue.
404
405Returns `true` if successful.
406
407#### .reset()
408
409Resets the state of `TimedNumber` object to its initial state.
410
411#### .getMaxValue()
412
413Returns maximum value.
414
415#### .getMinValue()
416
417Returns minimum value.
418
419#### .getInterval()
420
421Returns the interval for every update in milliseconds.
422
423#### .getStep()
424
425Returns the value of step for every update.
426
427#### .toObject()
428
429Returns a JSON format of `TimedNumber` object.
430
431You can reconstruct exact same timed number object from this JSON object.
432
433Example:
434
435```javascript
436var datetime = require('node-datetime');
437var config = {
438 max: 10,
439 min: 0,
440 interval: 1000,
441 step: 1,
442 type: 'inc',
443 init: 10
444};
445var timedNumber = datetime.createTimedNumber(conf);
446// do things
447timedNumber.dec(3);
448// store it in database as JSON
449var json = timedNumber.toOjbect();
450// read json back from the database and reconstruct timed number object
451var timedNumber2 = datetime.createTimedNumber(json);
452// timedNumber2 will have the same state as timedNumber
453```
454
455### .createTimedState(conf)
456
457Returns an instance of TimedState object that changes its state over time.
458
459conf:
460
461```
462{
463 states: [ 'A', 'B', 'C' ... ] // an array of states to represent the order of states
464 interval: 1000 // interval in milliseconds for the state to change
465 init: 0 // initial position of the states array
466 loop: false // if true, the states will loop
467}
468```
469
470Example:
471
472```javascript
473var datetime = require('node-datetime');
474var conf = {
475 states: [ 'one', 'two', 'three' ],
476 interval: 1000,
477 init: 0,
478 loop: false
479};
480// create the TimedState object that changes its state every 1 second from 'one' and it stops at 'three'
481var ts = datetime.createTimedState(conf);
482```
483
484### TimedState Class
485
486#### .getState()
487
488Returns the current state.
489
490#### .forward(position [*number])
491
492Forces the state to move forward by the given number. If no position is given, it will move forward by one.
493
494#### .backward(position [*number])
495
496Forces the state to move backward by the given number, If no position is given, it will move backward by one.
497
498#### .getStates()
499
500Returns the state array.
501
502#### .getInterval()
503
504Returns the interval in milliseconds
505
506#### .reset()
507
508Resets the state to its initial state.
509
510#### .toObject()
511
512Returns a JSON format of `TimedState` object.
513
514You can reconstruct exact same timed number object from this JSON object.
515