Extract Only Date from DateTime Object in Javascript?

DEO picture DEO · Jan 17, 2017 · Viewed 8.2k times · Source

i have Json Array which look like this and its working fine but i need to arrange them gruopwise like DateWise

 [ 
name: 'Ali',
startedAt: Wed Dec 28 2016 15:32:07 GMT+0500 (Pakistan Standard Time),
userId: '0002' },

{ completedAt: Wed Dec 28 2016 12:51:47 GMT+0500 (Pakistan Standard Time),
name: 'Aliy',
startedAt: Wed Dec 28 2016 12:43:19 GMT+0500 (Pakistan Standard Time),
userId: '212' },
{
name: 'Aliy',
startedAt: Wed Dec 28 2016 12:43:06 GMT+0500 (Pakistan Standard Time),
userId: '2121' }]

i have a code which groups them on the basis of startedAt and its working fine but the problem is that i want only date part like 28/12/2016

the below code is used for grouping

var groupedData = _.groupBy(datas, function(d){
   return d.startedAt});}

Answer

T.J. Crowder picture T.J. Crowder · Jan 17, 2017

On any modern browser, you can use the first 10 characters of the return value of toISOString:

var groupedData = _.groupBy(datas, function(d){
   return d.startedAt.toISOString().substring(0, 10);
});

The first ten characters are the year, then month, then date, zero-padded, e.g. 2017-01-17.

Note that that will group them by the day in UTC, not local time.

Also note that toISOString was added in 2009 as part of ES5.

If you need to support obsolete browsers that don't have it, or you need to use local time, just build a string from the parts of the date you need, padding as necessary, using getFullYear/getMonth/getDate or getUTCYear/getUTCMonth/getUTCDate as needed.