I have this date 21 ต.ค. 2022 06:10 PM
and i would like to change into 21 Oct 2022 06:10 PM
.
This is my code:
var date = "21 ต.ค. 2022 06:10 PM";
var monthNamesThai = ["ม.ค.", "ก.พ.", "มี.ค.", "เม.ย.", "พ.ค.", "มิ.ย.", "ก.ค.", "ส.ค.", "ก.ย.", "ต.ค.", "พ.ย.", "ธ.ค."];
// var monthNamesEng = ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"];
var monthNamesEng = ["Jan", "Feb", "Mar", "Apr", "May", "June", "July", "Aug", "Sept", "Oct", "Nov", "Dec"];
var d = new Date(date);
console.log("Change date " d " = " ('0' d.getDate()).slice(-2) " " monthNamesEng[d.getMonth()] " " d.getFullYear());
in which I get the output: Change date Invalid Date = aN undefined NaN
. Is there a simple way to change the Thai month names to English without using Moment.js? Thanks in advance
CodePudding user response:
var date = "21 ต.ค. 2022 06:10 PM";
var monthNamesThai = ["ม.ค.", "ก.พ.", "มี.ค.", "เม.ย.", "พ.ค.", "มิ.ย.", "ก.ค.", "ส.ค.", "ก.ย.", "ต.ค.", "พ.ย.", "ธ.ค."];
// var monthNamesEng = ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"];
var monthNamesEng = ["Jan", "Feb", "Mar", "Apr", "May", "June", "July", "Aug", "Sept", "Oct", "Nov", "Dec"];
const thaiMonth = date.substring(date.indexOf(" ") 1, date.indexOf(" ") 5)
console.log(date.replace(thaiMonth, monthNamesEng[monthNamesThai.indexOf(thaiMonth)]))
CodePudding user response:
make sure you Thai date always has the same format as this one, otherwise this will not work.
let date = "21 ต.ค. 2022 06:10 PM";
let monthNamesThai = ["ม.ค.", "ก.พ.", "มี.ค.", "เม.ย.", "พ.ค.", "มิ.ย.", "ก.ค.", "ส.ค.", "ก.ย.", "ต.ค.", "พ.ย.", "ธ.ค."];
let monthNamesEng = ["Jan", "Feb", "Mar", "Apr", "May", "June", "July", "Aug", "Sept", "Oct", "Nov", "Dec"];
// change Thai month to english month
let englishDate = date.split(" ");
englishDate.splice(1, 1, monthNamesEng[monthNamesThai.indexOf(date.split(" ")[1])]);
englishDate = englishDate.join(" ");
let d = new Date(englishDate);
console.log("Change date " d " = " ('0' d.getDate()).slice(-2) " " monthNamesEng[d.getMonth()] " " d.getFullYear());