Extract Only Date from DateTime Object in Javascript?
Asked Answered
T

1

9

I have an array which look like this and its working fine but I need to arrange them groupwise 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 it's 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(data, function(d) {
   return d.startedAt;
});
Turney answered 17/1, 2017 at 14:16 Comment(2)
I suggest you to use momentjs.comSlob
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.Lobby
L
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.

Lobby answered 17/1, 2017 at 14:18 Comment(5)
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 DateWiseTurney
@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.Lobby
You can also split on the ISOString "T": d.startedAt.toISOString().split("T")[0]Shuck
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.Emarie
@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.Lobby

© 2022 - 2024 — McMap. All rights reserved.