0
this.convertJSON_DateTimeTo_datetimeObj = function (jsonDate) {
            var date_dd_MM_yyyy = $filter('date')(jsonDate.slice(6, -2), 'medium');
            //var dt = new Date(date_dd_MM_yyyy).toLocaleString("en-US", { timeZone: "Asia/Kolkata" });
            //var dt = new Date(date_dd_MM_yyyy.split("/").reverse().join("/"));
            return date_dd_MM_yyyy;
        },

Input Parameter jsonDate = "/Date(1629810881857)/"

In the above code, I want to convert JSON DateTime into DateTime Object where the output timezone is "Asia/Kolkata". code in the comment is that which is already tried by me. It's very helpful for me if any body help me Thanks

  • 1
    Can you please include (part) of your `jsonDate`. We can't magically guess what it looks like. Check out [Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example) for more info – Reyno Aug 30 '21 at 06:41
  • based on the name of the variables I am guessing the date is in dd/mm/yyyy format. If yes, you need to convert to mm/dd/yyyy format to convert it to javscript Date object. https://stackoverflow.com/a/33299764/4018180 – Akshay G Aug 30 '21 at 07:50
  • Input Parameter jsonDate = "/Date(1629810881857)/" – Himanshu Aggarwal Aug 30 '21 at 10:07

1 Answers1

2

There are a few problems with this. First, the server isn't sending any timezone information in the /Date(1629810881857)/ string. This means you can't safely convert it to Asia/Kolkata timezone because you don't know what you're converting it from. You need to get the server to send that information in its response.

Once you solve that, you need to parse the date string into a JavaScript Date properly. Here's the best way. The $filter service shouldn't be needed here.

Lastly, it's best practice to let JavaScript dates convert to the end user's locale as defined in their browser/OS rather than forcing it to display in a particular timezone such as Asia/Kolkata. However, if you want to always display a particular timezone no matter where the user is located, here is a great answer explaining how that works.

Jacob Stamm
  • 1,660
  • 1
  • 29
  • 53
  • 1
    The term "locale" has been somewhat compromised by its use in ECMA-402 as a synonym for "language" (the *locale* parameter is a BCP-47 language tag) rather than location. So while the common meaning of locale should indicate timezone, in the context of ECMA-402 (i.e. *Intl.DateTimeFormat* and *toLocaleString*) it doesn't. Also, the location in OS settings isn't necessarily where the user is actually located, it's typically just the place that the OS gets its offset data from. :-) – RobG Aug 30 '21 at 15:08