我有一个日期,格式是2014年5月11日太阳。如何使用JavaScript将其转换为2014-05-11 ?

函数taskDate(dateMilli) { var d = (new Date(dateMilli) + ")。分割(' '); D [2] = D [2] + ','; 返回[d[0], d[1], d[2], d[3]]。加入(' '); } var datemilli =日期。解析(' 2014年5月11日'); console.log (taskDate (datemilli));

上面的代码给了我相同的日期格式,2014年5月11日。我该如何解决这个问题?


当前回答

重新格式化日期字符串是相当简单的,例如。

var s = ' 2014年5月11日'; 函数reformatDate(s) { 函数z(n){return ('0' + n).slice(-2)} var月=[‘简’,2月,3月,4月,“可能”,“君”, 7月,8月,9月,10月,11月,12月的]; var b = s.split(/\W+/); 返回b[3] + '-' + z (months.indexOf (b [1] .substr .toLowerCase (0, 3) ())) + '-' + z (b [2]); } console.log (reformatDate (s));

其他回答

这对我来说很有效,如果需要测试,你可以直接将它粘贴到你的HTML中:

<script type="text/javascript">
    if (datefield.type!="date"){ // If the browser doesn't support input type="date",
                                 // initialize date picker widget:
        jQuery(function($){ // On document.ready
            $('#Date').datepicker({
                dateFormat: 'yy-mm-dd', // THIS IS THE IMPORTANT PART!!!
                showOtherMonths: true,
                selectOtherMonths: true,
                changeMonth: true,
                minDate: '2016-10-19',
                maxDate: '2016-11-03'
            });
        })
    }
</script>

也要考虑时区,这一行程序不需要任何库就可以了:

new Date().toLocaleString("en-IN", {timeZone: "Asia/Kolkata"}).split(',')[0]

我们经常遇到这样的问题。每个解决方案看起来都很独特。但在php中,我们有处理不同格式的方法。在https://locutus.io/php/datetime/strtotime/上有一个php的strtotime函数的端口。 一个小的开源npm包,作为另一种方式:

<script type="module">
import { datebob } from "@dipser/datebob.js";
console.log( datebob('Sun May 11, 2014').format('Y-m-d') ); 
</script>

看到datebob.js

这是另一种答案组合。可读性很好,但有点长。

function getCurrentDayTimestamp() {
  const d = new Date();

  return new Date(
    Date.UTC(
      d.getFullYear(),
      d.getMonth(),
      d.getDate(),
      d.getHours(),
      d.getMinutes(),
      d.getSeconds()
    )
  // `toIsoString` returns something like "2017-08-22T08:32:32.847Z"
  // and we want the first part ("2017-08-22")
  ).toISOString().slice(0, 10);
}

如果日期需要在所有时区都相同,例如表示数据库中的某个值,那么请确保在JavaScript date对象上使用UTC版本的日、月、年函数,因为这将以UTC时间显示,并避免在某些时区出现差一的错误。

更好的是,使用Moment.js日期库来进行这种格式设置。