jQuery converting datetime to specific format

30,753

Solution 1

You can always use moment.js ( http://momentjs.com/ )

It's one of the easiest methods to manipulate with Date and Time.

Using moment you can easily covert by :

moment(new Date()).format('yyyy-MM-dd');

Solution 2

moment(yourdate, 'DD/MM/YYYY HH:mm').format("DD/MM/YYYY HH:mm");

Share:
30,753
User987
Author by

User987

Updated on July 09, 2022

Comments

  • User987
    User987 almost 2 years

    I have a datetime which gets returned from server side in my .net application like following:

    Jul 24 2017  7:33PM
    

    I have tried to convert it into:

    yyyy-MM-dd
    

    format like following:

    var date = new Date(data);
     var res = (date.getFullYear() + '-'(date.getMonth() + 1) + '-' + date.getDate());
    

    But when I output the result in console the result I get is:

    NaN-NaN-NaN
    

    How can I convert the time in jQuery/Javascript into yyyy-MM-dd format?

    Can someone help me out?

    P.S. Guys here is the query that returns the results and dates that I'm trying to convert:

         var user = ctx.Users.Where(x => x.UserId == _parsedId)
                    .Select(b => new
                    {
                        Active = b.Active,
                        Email = b.Email,
                        Subscriptions = b.Subscriptions.Where(p => p.Active == true).Select(sub => new
                        {
                            SubscriptionID = sub.SubscriptionId,
                            Type = sub.SubTypes.SubName,
                            ReferenceID = sub.ReferenceId,
                            Active = sub.Active,
                            DateCreated = sub.CreateDate.ToString("yyyy-MM-dd"),
                            ExpirationDate = sub.ExpirationDate.ToString("yyyy-MM-dd")
                        }).ToList(),
                        Roles = b.UserRoles.Where(p => p.Active == true).ToList()
                    })
                    .AsEnumerable()
                    .Select(x => x)
                    .FirstOrDefault();
    
    
       // ExpirationDate - is of Type DateTime?
       // CreatedDate - is of Type DateTime 
    

    And when I try to convert the datetime to specific format I get a following error:

    Additional information: LINQ to Entities does not recognize the method 'System.String ToString(System.String)' method, and this method cannot be translated into a store expression.

    • Peter B
      Peter B over 6 years
      If possible, make the server output a better structured format such as the yyyy-MM-dd that you mentioned. Would save a lot of headaches on the client side.
    • Admin
      Admin over 6 years
      new Date(Jul 24 2017 7:33PM); returns InvalidDate
    • Kaddath
      Kaddath over 6 years
      "Note: Parsing of strings with Date.parse is strongly discouraged due to browser differences and inconsistencies." (Date.parse is what uses the constructor when string passed) - see here
    • User987
      User987 over 6 years
      @StephenMuecke A yes, I guess Peter made a good suggestion to change it in server side and avoid conversions in client side ... ?
    • User987
      User987 over 6 years
      Guys, I've pasted my server side code with conversion to specific format, but I'm getting an error here...
    • Titus
      Titus over 6 years
      If you can use the moment.js library you can do something like this moment("Jul 24 2017 7:33PM", "MMM DD YYYY hh:mmA").format("DD-MM-YYYY")
    • Admin
      Admin over 6 years
      You can always make the property string
    • User987
      User987 over 6 years
      @StephenMuecke I'm using an anonymous type, would that be even possible? xD
    • Admin
      Admin over 6 years
      Yes, but only my materializing the query first ( ctx.Users.Where(x => x.UserId == _parsedId).AsEnumerable().Select(... ) and then converting to a formatted string. But how are you using this and why do you need it in that format
    • User987
      User987 over 6 years
      @StephenMuecke hm this is quite odd, when doing AsEnumerable() I'm getting empty collections Subscriptions and Roles, but I know for a fact they should have at least 2 elements inside ? :/
    • Zaheer Ul Hassan
      Zaheer Ul Hassan over 6 years
      did you try sub.CreateDate.Date.ToString("yyyy-MM-dd") ??
    • Admin
      Admin over 6 years
      You might need a .Include(x => x.Subscriptions) etc
    • User987
      User987 over 6 years
      @StephenMuecke a yes correct , gonan try it now =)
    • User987
      User987 over 6 years
      @StephenMuecke I did include all nearby tables and I'm getting circular reference error now xD
    • Admin
      Admin over 6 years
      Best guess is that UserRoles contains a reference back to Users, and that you returning a JsonResult - you should also create an anonymous object for Roles containing only the properties your need. (note also you do not need your .Select(x => x))
    • Sindhoor
      Sindhoor over 6 years
      alert(date); and check is it giving correct date?
  • User987
    User987 over 6 years
    Hey Sagar, by doing this , for example input date: Jul 24 2017 7:33PM gets output like: 2017-10-03 , which isn't correct at all
  • Sagar
    Sagar over 6 years
    Hello there, I tried and got the correct result. Can you please send the exact date so I can recheck.