Wednesday, 26 August 2015

In Detail: Date In JavaScript

In JavaScript, a date represents both date and time. As per ECMAScript specification, date is stored as a time value internally. A time value is a primitive number that stores date as milliseconds since 1 January 1970 00:00:00 UTC.

The maximum and minimum dates you can store in date object are
Max Date:
Exactly 100,000,000 days after 1 January 1970 00:00:00
var d = new Date(8640000000000000); // Sat Sep 13 275760 05:30:00 GMT+0530 (India Standard Time)

Minimum Date:
Exactly 100,000,000 days before 1January 1970 00:00:00
var d = new Date(-8640000000000000); //Tue Apr 20 -271821 05:30:00 GMT+0530 (India Standard Time)

Let's see how to create Date types in JavaScript

Using Date() constructor you can construct a new date from the given data. The constructor has 4 different signatures.

1.    Date()
2.    Date(timeValue)
3.    Date(dateString)
4.    Date(year, month, date, hours, minutes, seconds, milliseconds)

Let’s see some examples.

Date():
    The Date() constructor with no arguments is used to construct a date object with current date and time.
var currentDate = new Date();

console.log(currentDate); // Mon Aug 24 2015 18:27:34 GMT+0530 (India Standard Time)

Date(timeValue):
    You can create a date by passing time value, which represents number of milliseconds since 1st January 1970 00:00:00 UTC. For example:
var date = new Date(0); 

console.log(date); // Thu Jan 01 1970 05:30:00 GMT+0530 (India Standard Time)

Date(datestring):
In the above call, the dateString will be converted into a number, and then new Date(timeValue) is invoked by passing the converted number. The converted number represents no of milliseconds since 1 January 1970 00:00:00 UTC. For example.
var date = new Date('2012-12-22');

console.log(date); // Sat Dec 22 2012 05:30:00 GMT+0530 (India Standard Time)
Illegal strings to the Date(dateString) constructor lead to NaN as an argument to the new Date(number), which results an invalid date.
var date = new Date("abc");

console.log(date); // Invalid Date
Constructing date object with given data:
You can pass parameters such as year, month, date, hours, minutes, seconds, milliseconds to date constructor to create new date object. For example,
var date = new Date(1990,11,22,10,30,00);

console.log(date); // Sat Dec 22 1990 10:30:00 GMT+0530 (India Standard Time)
you need to pass at least two parameters to the date constructor, such as year & month, to distinguish from other Date(timeValue) constructor.
calling Date constructor with atleast 2 params
var date = new Date(1990,11);

console.log(date); // Sat Dec 01 1990 00:00:00 GMT+0530 (India Standard Time)
The time is interpreted relative to the current time zone. In the above example you can see GMT + 0530 as current time zone.
The parameters have the following ranges:
Year – any valid year. Values from 0 to 99 mapped to years 1900 to 1999.

Month – 0 to 11 (inclusive) – 0 is January, 1 is February, etc.

Date – 1 to 31 (inclusive)

Hours – 0 to 23 (inclusive)

Minutes – 0 to 59 (inclusive)

Seconds – 0 to 59 (inclusive)

Milliseconds – 0 to 999 ( inclusive)
Just like Java, JavaScript interprets 0 as January, 1 as February, and so on.

Date Constructor Properties and Methods:
Methods such as now(), parse(varStr), UTC(year,month,date,hours,minutes, seconds, milliseconds) don't require a Date instance. You can just access using "." operator on Date constructor.
Date.now():
 Returns the current date and time in milliseconds, since 1 January 1970, 00:00:00 UTC.
var now = Date.now();

console.log(now); // 1440513842142
Date.parse(dateTimeString):
It converts the passed dateTimeString to milliseconds since 1st January 1970, 00:00:00 UTC and returns the result.
Date.parse("2012-12-22");  // 1356134400000

If a non formatted string is passed, then it returns NaN:

Date.parse("abc"); // NaN
Date.UTC(year, month, date, hours, minute, seconds, milliseconds) :
Converts the given date to miliseconds since 1st January 1970 00:00:00 UTC and returns the result. It interprets the arguments as UTC, rather than as local time.

Date.length:
Returns 7, which represents number of arguments to the parameterized Date Constructor.

Date Prototye Methods:
Let's create a Date object first, and will see differnt methods
var d = new Date(); // Tue Aug 25 2015 23:25:53 GMT+0530 (India Standard Time)

Getters:
getYear(): Returns difference between the year and 1900. It is deprecate, use getFullYear() instead.
For example
d.getYear(); // 115 - i.e difference between 2015 and 1900
getFullYear(): Returns actual year represented by the date object.
d.getFullYear(); // 2015 
getMonth(): Returns an integer between 0 and 11. 0 represents January, 1 – february and so on.
d.getMonth(); // 7
getDate(): Returns day of the month (1-31).
d.getDate(); // 25
getDay(): Returns day of the week (0-6). 0 represents Sunday, 1 – Monday and so on.
d.getDay(); // 2 i.e tuesday
getHours(): Returns Hour ( 0 – 23).
d.getHours(); // 23
getMinutes(): Returns Minutes of Hour ( 0 – 59).
d.getMinutes(); // 29
getSeconds(): Returns seconds ( 0 –59).
d.getSeconds(); // 47
getMilliSeconds(): Returns milliseconds (0 –999)
d.getMilliSeconds(); // 901
getTime(): Returns the milliseconds since 1 January 1970 00:00:00 UTC.
d.getTime(); // 1440525587901
getTimezoneOffset(): Time zone off set is difference between UTC and local time in minutes. This method returns the difference.
d.getTimezoneOffset(); // -330 ( UTC + 5:30).
valueOf(): Returns the number of milliseconds same as getTime().
d.valueOf(); // 1440525587901
setTime(timeValue): Sets the date as specified in milliseconds since 1 January 1970 00:00:00 UTC.
var d2 = new Date(2016,11,22); 

D1.setTime(d2.getTime()); //  Thu Dec 22 2016 00:00:00 GMT+0530 (India Standard Time)

console.log(d1); // Tue Aug 25 2015 23:29:47 GMT+0530 (India Standard Time)
SetYear(number): Sets the number as year according to the local time. If the passed number is between 0 an d99, then the year is set to 1900 + number. For example.
Var d1 = new Date();

Console.log(d1); // Wed Aug 26 99 00:06:34 GMT+0530 (India Standard Time)

D1.setYear(99); 

Console.log(d1); // Thu Aug 26 1999 00:02:36 GMT+0530 (India Standard Time)
This method is deprecated, use setFullYear() instead.

SetFullYear(year, month?, date?) :
Sets the full year for a specific date object according to the local time. Year is mandatory, month and date are optional.
Var d1 = new Date(); // Wed Aug 26 2015 00:06:34 GMT+0530 (India Standard Time)

D1.setYear(99); // Wed Aug 26 99 00:06:34 GMT+0530 (India Standard Time)

Converting a Date to a String:

As JavaScript date stores both date and time information in it, you can get the date and time values separately using below methods. 

Converting only Time portion:

toTimeString(): Returns the time in human-readable format.
Var d = new Date(); //Wed Aug 26 2015 00:11:58 GMT+0530 (India Standard Time)

d.getTimeString(); // 00:11:58 GMT+0530 (India Standard Time)
toLocaleTimeString(): Returns the time string in locale-specific format.
d.toLocaleTimeString(); // "00:11:58"
Conversion functions for date portion:

toDateString(): Returns the date string.
d.toDateString(); // "Wed Aug 26 2015"
toLocaleDateString(): Returns the date string in locale-specific format.
d.toLocaleDateString(); // "26/08/2015"
Converting entire Date and Time:

toString(): Returns string form of Date and Time in the current Time Zone.
d.toString(); // "Wed Aug 26 2015 00:11:58 GMT+0530 (India Standard Time)"
toLocaleString(): Returns string form of Date and Time in locale specific format.
d.toLocaleString(); // "26/08/2015, 00:11:58"
toUTCString(): Returns string form of Date and time in UTC format.
d.toUTCString(); // "Tue, 25 Aug 2015 18:41:58 GMT"
toISOString(): Returns a machine readable format of Date and Time.
d.toISOString(); // "2015-08-25T18:41:58.278Z"
The time zone is always Z here.

toJSON(): Converts the date object to JSON strings and returns. It internally calls to ISOString().
d.toJSON(); // "2015-08-25T18:41:58.278Z"
Date TimeFormat:
When ever you want to use methods such as Date.parse(dateTimeStr), new Date(dateTimeStr), you need to follow a specific format for this.
The format as per ECMA-Script 5 is
YYYY-MM-DDTHH:mm:ss.sssZ
For example
var d = new Date("2015-08-26T10:07:00Z"); // Wed Aug 26 2015 15:37:00 GMT+0530 (India Standard Time)
Each part has some significance in date time. For example
YYYY stands for 4 digit year.

MM stands for 2 digt month ( 1-12),

DD is for date ( 1 – 31)

HH – Hours ( 0 –11)

Mm - Minutes ( 0 – 59)

Ss - seconds ( 0 – 59)

Sss - (0 – 999)
The method toISOString() returns date in this format only. For example
Var d = new Date();

d.toISOString(); // 2015-08-26T02:40:29.281Z
The above format is longest date format, which includes both date and time. There are other formats only for Dates and Times. For example, if you want to pass only date portion, without time part such as "2015-11-22", the following formats are available.

Only Date Formats:
You can pass, only date portion to Date constructor, the format is as follows.

YYYY-MM-DD, 
YYYY-MM,
YYYY
Here YYYY refers to year, MM – month (01-12), DD referes to day ( 01-31).
For example
var d = new Date("2016-12-22"); // Thu Dec 22 2016 05:30:00 GMT+0530 (India Standard Time)

var d = new Date("2016-12"); //  Thu Dec 01 2016 05:30:00 GMT+0530 (India Standard Time)

var d = new Date("2016"); // Fri Jan 01 2016 05:30:00 GMT+0530 (India Standard Time)

Only Time Formats:
If you want to construct date with only time (10:25:12), you can follow below time formats
THH:mm:ss.sss

THH:mm:ss.sssZ

THH:mm:ss

THH:mm:ssZ

THH:mm

THH:mmZ
You need to prefix the time part with Literal T, it represents the start of the time portion.
HH – refers to hour, from 00 to 23
mm – indicates minute, from 00 to 59
ss – indicates seconds, from 00 to 59
sss – indicates milliseconds from 000 to 999
Z – refers to time zone, here it represents UTC time format
For example,
var d = new Date("T10:01:00Z");  // run in firefox, won’t work in chrome – only some JS engines allows you to specify only a time.

console.log(d); // Date 1970-01-01T10:01:00.000Z

Comparing Dates:
You can use the relational operators such as > , < , >= , <= to compare JavaScript dates. However, the equality operators ==, !==, ===, !=== cannot be used, instead convert date to time value and check for equality.

Comparing dates with relational operators:
Lets take two dates.
Var d1 = new Date(“2015-08-26”);

Var d2 = new Date(“2015-12-22”);

D1 > d2; // false – d1 is smaller

D1 < d2; // true 

D1 >= d2; // false 

D1 <= d2; // true

Comparing for equality:
If you want to compare for equality, don't use == or ===. Get the date in milliseconds and use == or === operators.

var d1 = new Date(“2015-08-26”);

var d2 = new Date(“2015-08-26”);

dv1 == d2; // false, two objects can never be equal,

d1.getTime() === d2.getTime(); // true, converts to number (time value) and checks for equality.


0 comments:

Post a Comment

Note: only a member of this blog may post a comment.