我的日期为字符串"20180619"
如何将此转换为19 Jun 2018
我开始尝试
var date = new Date(parseInt("20180619"));
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
console.log(d + ' ' + m + ' ' + y)
但是获得1 0 1970
编辑:所以这里实际上有2个问题,首先是日期是错误的格式,第二个是月份名称。第二部分是另一个相关问题的答案。所以它只是归结为在这里的答案中使用几种不同的方法之一将日期分解为它的组件。
答案 0 :(得分:2)
我有toLocaleString
的新简单解决方案:
var str = '20180619';
var date = new Date([str.slice(0, 4), str.slice(4, 6), str.slice(6, 8)].join('/'));
var result = date.toLocaleString('en-GB', { month: 'short', year: "numeric", day: "2-digit"})
console.log(result);
答案 1 :(得分:1)
您需要将字符串解析为Date可以理解的内容。怎么样:
var dateString = "20180619";
var parsedDate = dateString.replace(/(\d{4})(\d{2})(\d{2})/, '$1/$2/$3');
var date = new Date(parsedDate);
var d = date.getDate();
var months = ['Jan', 'Feb', 'Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
var m = months[date.getMonth()];
var y = date.getFullYear();
console.log(d + ' ' + m + ' ' + y)
结果为19 Jun 2018
答案 2 :(得分:1)
以给定模式构建日期对象,即yyyy-mm-dd
或dd-mm-yyyy
,其中分隔符可以是-
或/
var date = new Date("20180619".replace(/(\d{4})(\d{2})(\d{2})/, '$1-$2-$3'));
var str = [date.getDate(), (['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][date.getMonth()]), date.getFullYear()].join(' ');
console.log(str);
var str = "20180619".replace(/(\d{4})(\d{2})(\d{2})/, function(o, y, m, d) {
return [d, ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][parseInt(m, 10) - 1], y].join(' ');
});
console.log(str);
答案 3 :(得分:0)
将日期字符串转换/拆分为数组,然后使用数组索引获取值并创建Date对象。
在这里,我为您创建了一个简单的JSFiddle。
var dateString = "20180619";
var dateArray = dateString.split("");
console.log(dateArray);
var myDate = new Date();
console.log(myDate.toString());
myDate.setFullYear(dateArray[0] + dateArray[1] + dateArray[2] + dateArray[3]);
myDate.setMonth(dateArray[4] + dateArray[5]);
myDate.setDate(dateArray[6] + dateArray[7]);
console.log(myDate.toString());
日期部分的格式仍然缺失。我希望你能够自己动手。
答案 4 :(得分:-1)
var date = new Date("06/19/2018"); //You were providing the date in a wrong format.
const monthNames = ["January", "February", "March","April","May","June","July","August","September","October","November","December"];
var newDate = date.getDate() + ' ' + monthNames[date.getMonth()] + ' ' + date.getFullYear();