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


当前回答

formatDate(date) {
  const d = new Date(date)
  const ye = new Intl.DateTimeFormat('en', { year: 'numeric' }).format(d);
  const mo = new Intl.DateTimeFormat('en', { month: 'short' }).format(d);
  const da = new Intl.DateTimeFormat('en', { day: '2-digit' }).format(d);
  return `${da}-${mo}-${ye}`;
}

console.log("Formatated Date : ", formatDate("09/25/2020") )
// Output :: Formatated Date : 25-Sep-2020

其他回答

我建议使用类似formatDate-js的东西,而不是每次都试图复制它。只需使用一个支持所有主要strftime操作的库。

new Date().format("%Y-%m-%d")

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

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

我用这种方式获取日期格式为yyyy-mm-dd:)

var todayDate =新日期。slice (0) (10); 游戏机。log (todayDate);

使用joda-js并完成它:

import { DateTimeFormatter, LocalDateTime } from 'js-joda'

const now = LocalDateTime.now()
now.format(DateTimeFormatter.ofPattern('yyyyMMdd-HH:mm:ss'))
// Outputs: 20221104-09:25:09 according to your timezone (mine is 'America/New_York'

不需要库

纯JavaScript。

下面的例子是从今天开始的两个月:

var d = new Date() d.setMonth(d.getMonth() - 2); var dateString =新的日期(d); console.log('格式化前',dateString, '格式化后',dateString. toisostring ().slice(0,10))