我有一个日期,格式是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日。我该如何解决这个问题?


当前回答

我们经常遇到这样的问题。每个解决方案看起来都很独特。但在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

其他回答

以下是一些答案的组合:

var d = new Date(date);
date = [
  d.getFullYear(),
  ('0' + (d.getMonth() + 1)).slice(-2),
  ('0' + d.getDate()).slice(-2)
].join('-');

简单地使用这个:

var date = new Date('1970-01-01'); // Or your date here
console.log((date.getMonth() + 1) + '/' + date.getDate() + '/' +  date.getFullYear());

简单又甜蜜;)

函数 myYmd(D){ var pad = function(num) { 变量 s = '0' + 数字; 返回 s.substr(s.length - 2); } var Result = D.getFullYear() + '-' + pad((D.getMonth() + 1)) + '-' + pad(D.getDate()); 返回结果; } var datemilli = new Date('Sun May 11,2014'); document.write(myYmd(datemilli));

我们经常遇到这样的问题。每个解决方案看起来都很独特。但在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

这是我必须改变的关于人们从格林威治标准时间向东或向西的偏移量:

export const toNativeHtml5InputDate = (date) => {
  if (!date) return date;

  let offset = new Date(date).getTimezoneOffset();

  offset =
    offset < 0
      ? offset * -1 // east from Greenwich Mean Time
      : offset; // west from Greenwich Mean Time

  return new Date(new Date(date).getTime() + offset * 60 * 1000)
    .toISOString()
    .split('T')[0];
};