0

I have a JavaScript method which gets current date and returns its universal time. Below is the code:

 function calUTCTime(offset) {

        var currentDate = new Date();    

        var utc = currentDate.getTime() - (currentDate.getTimezoneOffset() * 60000);

        var result = new Date(utc + (3600000 * offset));

        return result .toLocaleString();
    }

Above code is returning wrong date, it is replacing date with month and date format in my system is dd-MM-yyyy, OS is Windows 8. I tried on other system's and the date is correct but on my system it is wrong. Please share suggestions.

NMathur
  • 829
  • 1
  • 17
  • 35
  • 2
    That is exactly what I would expect from `.toLocaleString();`. The browser is determining your language (or "locale") from the OS and using it in that method to determine how to output the string. Try `.toString();` instead. See [the difference](http://stackoverflow.com/questions/11945272/javascript-difference-between-tostring-and-tolocalestring-methods-of-date). – Cᴏʀʏ Sep 02 '14 at 11:42
  • Why are you creating a new Date? use `.toUTCString()` if you want to format a date in the UTC offset. – Sacho Sep 02 '14 at 11:56
  • @Sacho .. I have not tried .toUTCString() .. but I think it will need a date to convert to universal date .. right?? .. I universal date time of current date that is why I used "new Date()". – NMathur Sep 02 '14 at 12:36
  • 1
    UTC and are two ways of *displaying* a date. You don't need to 'convert' a date(which is a fixed point in time) to a 'universal date'. – Sacho Sep 02 '14 at 12:50
  • @Cary and Sacho .. solution given by Cory worked .. thanks both for you :) – NMathur Sep 02 '14 at 12:58
  • @NMathur: I have expanded upon my comment in an answer. – Cᴏʀʏ Sep 02 '14 at 14:00

1 Answers1

1

That is exactly what I would expect from .toLocaleString(). The browser is determining your language (or "locale") from the OS and using it to choose how to output the string. If you want a generic human-readable date format, try a simple .toString() instead.

If you want complete and total control over how a date is formatted, try a library like moment.js. For example, your above code could be condensed to:

return moment().utc().format("YYYY-MM-DD"); // "2014-09-02"

There is another post that summarizes the differences between the two methods: JavaScript: Difference between toString() and toLocaleString() methods of Date

Community
  • 1
  • 1
Cᴏʀʏ
  • 105,112
  • 20
  • 162
  • 194