最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - toISOString() return wrong date - Stack Overflow

programmeradmin2浏览0评论

Why did this piece of code return tomorrow's date ?

It must return 2013-08-31 and not 2013-09-01 as we are August 31st.

.asp?filename=tryjsref_toisostring

function myFunction() {
  var d = new Date();
  var x = document.getElementById("demo");
  x.innerHTML = d.toISOString();
}
<p id="demo">Click the button to display the date and time as a string, using the ISO
  standard.</p>
<button onclick="myFunction()">Try it</button>

Why did this piece of code return tomorrow's date ?

It must return 2013-08-31 and not 2013-09-01 as we are August 31st.

http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_toisostring

function myFunction() {
  var d = new Date();
  var x = document.getElementById("demo");
  x.innerHTML = d.toISOString();
}
<p id="demo">Click the button to display the date and time as a string, using the ISO
  standard.</p>
<button onclick="myFunction()">Try it</button>

Share Improve this question edited Nov 28, 2016 at 23:57 display name 4,1852 gold badges31 silver badges55 bronze badges asked Sep 1, 2013 at 1:24 FrancoisFrancois 2952 gold badges5 silver badges11 bronze badges 4
  • developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… – Nayuki Commented Sep 1, 2013 at 1:26
  • 1 How can I take MY jour and not UTC one ? – Francois Commented Sep 1, 2013 at 1:27
  • Just see this post: stackoverflow.com/questions/16084313/… – Francois Commented Sep 1, 2013 at 1:28
  • stackoverflow.com/questions/18551331/fullcalendar-date-format – H.D. Commented Sep 1, 2013 at 2:49
Add a comment  | 

3 Answers 3

Reset to default 6

It's in UTC.

If you want to get your local timezone you have to format the date yourself (using getYear() getMonth() etc.) or use some library like date.js that will format the date for you.

With date.js it's pretty simple:

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

edit

As @MattJohnson noted date.js has been abandoned, but you can use alternatives like moment.js.

use:

new Date().toLocaleDateString('pt-br').split( '/' ).reverse( ).join( '-' );

or

(function() {

    function pad(number) {
      if (number < 10) {
        return '0' + number;
      }
      return number;
    }

    Date.prototype.toISO1String = function() {
      return this.getFullYear() +
        '-' + pad(this.getMonth() + 1) +
        '-' + pad(this.getDate()) +
        'T' + pad(this.getHours()) +
        ':' + pad(this.getMinutes()) +
        ':' + pad(this.getSeconds()) +
        '.' + (this.getMilliseconds() / 1000).toFixed(3).slice(2, 5) +
        'Z';
    };

  })();

See: mozilla.org toISOString doc

I just modified it

You can simply use Luxon.

DateTime.fromJSDate(new Date(yourDateVariable)).toFormat('yyyy-MM-dd')
发布评论

评论列表(0)

  1. 暂无评论