8

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});}
DEO
  • 316
  • 2
  • 4
  • 18
  • I suggest you to use https://momentjs.com – Ergec Jan 17 '17 at 14:22
  • Note that your code at the end has a syntax error (extra `}`). Which is an excellent advertisement for why putting the closing `}` on the same line as the last statement of a block is an awkward and error-prone bracing style. – T.J. Crowder Jan 17 '17 at 14:22

1 Answers1

10

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.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • thanks it works but can you please guide me through that how will i b able to show it in my Views e.g iam using Marko as view template . Can you tell me that how can i show it DateWise – DEO Jan 18 '17 at 04:52
  • @DEO: Your best bet there is to give it a go, and if you run into a specific problem, post a question about that problem with your attempt and what's wrong with it. – T.J. Crowder Jan 18 '17 at 07:39
  • You can also split on the ISOString `"T"`: `d.startedAt.toISOString().split("T")[0]` – phoenix Aug 19 '20 at 18:58
  • 1
    `toISOString()` causes issues with timezones when the time is `00:00:00`. try `new Date('1984-12-23T00:00:00').toISOString()` when your timezone is not UTC. – Muhammad Hewedy Jun 16 '22 at 08:17
  • @MuhammadHewedy - *"Note that that will group them by the day in UTC, not local time."* If the OP wants local time, they have to do what I describe later in the answer. – T.J. Crowder Jun 16 '22 at 08:20