gpt4 book ai didi

javascript - 将字符串转换为 JS 日期

转载 作者:行者123 更新时间:2023-11-28 11:36:29 25 4
gpt4 key购买 nike

我正在尝试将字符串值转换为 JavaScript 日期格式,但我似乎没有找到一种简单的方法来做到这一点,而无需使用其他库(例如 datejs)

var dateString = "20131120";
var date = new Date(dateString);
console.log(date);
// I need to add an additional day to the original string
var newDate = date.getFullYear() + '-' + (date.getMonth()+1) + '-' + (date.getDate()+1);
console.log(newDate);

非常感谢任何提示。

最佳答案

你能试试这个代码吗

 var dateString  = "20131120";
var year = dateString.substring(0,4);
var month = dateString.substring(4,6);
var day = dateString.substring(6,8);
var date = new Date(year, month-1, day);

这里只是使用了简单的子字符串方法

First (0,4) will extract the year then next two is for month and next two is for day of month

NOTE:
Here we doing `month-1` because it will count from 0 e.g (january==0).

希望对你有帮助

关于javascript - 将字符串转换为 JS 日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19028284/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com