【问题标题】:Convert string date to datetime js [duplicate]将字符串日期转换为日期时间 js [重复]
【发布时间】:2021-08-11 19:22:10
【问题描述】:

我被 javascript 困住了。 我从 JSON 获取示例字符串:

Saturday 14th August

如何转换成

 14/08/2021

谢谢。

【问题讨论】:

  • 如何从字符串中获取年份?
  • @svarog 的常见做法是在未指定年份的情况下获取当前年份。
  • 你如何避免将来意外获得约会?

标签: javascript date datetime


【解决方案1】:

您可以使用Pure Javascript 来实现更多逻辑。我的建议是使用Moment.Js 这是处理复杂 DateTime 数据的一种非常简单的方法。

检查此工作代码:

const dateString = "Saturday 14th August";
const formattedDate = moment(dateString, "dddd Do MMMM").format("DD/MM/Y");

console.log(formattedDate);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

注意:

正如评论中提到的@svarog,很难找到年份,如果没有提供。但是通常的做法是获取当前年份。 Moment JS 处理得很好。

【讨论】:

  • MomentJS 是 2021 年未维护的库
  • 谢谢。工作:)
  • @GaëlJ—moment.js 并非无人维护,它被认为是“a legacy project in maintenance mode”。但是,是的,建议不要将它用于新项目。此外,还有许多非常小的日期库,它们是解析和格式化或简单的 3 行函数的好选择。
【解决方案2】:

let jsonDateString = "Saturday 14th August" 
//this is the string you get 

let jsonDateStringArray = jsonDateString.split(" "); 
//here we split the words so we can better manipulate them

let month = jsonDateStringArray[2]; 
//we save the month here

let day = jsonDateStringArray[1].replace(/\D/g, ""); 
//saving the day and removing everything but numbers

let year = new Date().getFullYear(); 
//creating a date so we can get the year without having to hardcode it


let completeDate = new Date(Date.parse(month + ' ' + day + ', ' + year));
//create a new date from the string we pass 'August 14, 2021'


console.log(completeDate.toLocaleDateString('en-GB'));
//parameter en-GB for 14/08/21, without parameter we get 08/14/2021

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2012-01-02
  • 1970-01-01
  • 2016-07-30
  • 2015-09-17
  • 1970-01-01
  • 1970-01-01
  • 2012-05-16
相关资源
最近更新 更多