[英]Converting string m/dd/yyyy HH:MM:SS to date dd-mm-yyyy in Javascript
I have a string that looks like '1/11/2018 12:00:00 AM' and I want to reformat it to dd-mm-yyyy. 我有一个看起来像'1/11/2018 12:00:00 AM'的字符串,我想将其重新格式化为dd-mm-yyyy。 Keep in mind that the month can be double digit sometimes.
请记住,有时月份可能是两位数。
You can do somethink like this : 您可以这样做:
var d = new Date();
var curr_date = d.getDate();
var curr_month = d.getMonth() + 1; //Months are zero based
var curr_year = d.getFullYear();
console.log(curr_date + "-" + curr_month + "-" + curr_year);
However best way is with Moment.js,where you can Parse, Validate, Manipulate, and Display dates in JavaScript. 但是,最好的方法是使用Moment.js,您可以在其中使用JavaScript解析,验证,操作和显示日期。
example: 例:
var date= moment("06/06/2015 11:11:11").format('DD-MMM-YYYY');
You can use libraries like moment.js. 您可以使用诸如moment.js之类的库。 Assuming either you do not want to use any external library or can not use it, then you can use following custom method:
假设您不想使用任何外部库或不能使用它,那么可以使用以下自定义方法:
function formatDate(dateStr) {
let date = new Date(dateStr);
let day = date.getDate();
let month = date.getMonth() + 1;
let year = date.getFullYear();
return day + '-' + month + '-' + year;
}
console.log(formatDate('1/11/2018 12:00:00 AM'));
function convertDate(oldDate) {
var myDate = new Date(Date.parse(oldDate)); //String -> Timestamp -> Date object
var day = myDate.getDate(); //get day
var month = myDate.getMonth() + 1; //get month
var year = myDate.getFullYear(); //get Year (4 digits)
return pad(day,2) + "-" + pad(month, 2) + "-" + year; //pad is a function for adding leading zeros
}
function pad(num, size) { //function for adding leading zeros
var s = num + "";
while (s.length < size) s = "0" + s;
return s;
}
convertDate("1/11/2018 12:00:00 AM"); //11-01-2018
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.