![](/img/trans.png)
[英]Javascript convert yyyy-mm-dd hh:mm:ss like newDate(“day, month date year hh:mm:ss”)
[英]Combine date (day-month-year) and time (hh:mm am/pm) and convert it to unix format (javascript)
我有变量 oldDate 和 b。 我想将它们组合起来并转换成 unix 格式。 oldDate 具有日-月-年格式。 转换为 unix 后,似乎月月如一日。 有没有更好的方法来做到这一点,还是我需要先将 oldDate 转换为月-日-年格式?
var oldDate = '10-03-2021';
var b = '7:45 AM';
var newB = oldDate + " " + b;
var bDate = new Date(newB).getTime();
console.log(bDate);
output: 1633218300000
类似的东西?
function date2unix(oldDate, bTime)
{
let [d,m,y] = oldDate.split('-').map(Number)
, [h,mn,ap] = bTime.split(/:| /).map(s=>Number(s)||(/pm/i.test(s)?12:0))
;
return new Date( y, --m, d, (h % 12) +ap, mn, 0 ).getTime()
}
示例用法:
function date2unix(oldDate, bTime) { let [d,m,y] = oldDate.split('-').map(Number), [h,mn,ap] = bTime.split(/:| /).map(s=>Number(s)||(/pm/i.test(s)?12:0)); return new Date( y, --m, d, (h % 12) +ap, mn, 0 ).getTime() } let oldDate = '10-03-2021', b = '7:45 AM'; let unixDate = date2unix(oldDate, b) console.log('oldDate =', oldDate, `\n`, ' b =', b, `\n ----->` ) console.log('unixDate =', unixDate ) /* -- verif -- */ const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' } let verifDate = new Date(unixDate) console.log('\nverif:\n', verifDate.toLocaleString(), `\n`, verifDate.toLocaleString('en-US',options) )
.as-console-wrapper { max-height: 100%;important: top; 0; }
_ 12am 是午夜(00:xx)
_ 12pm 是中午 ( 12:xx )
见https://en.wikipedia.org/wiki/12-hour_clock
// on AM -> ap = 0
// on PM -> ap = 12
// ... so :
if (h===12) h = 0 // then h + ap will return the correct hour value
// or simply (without if)
h %= 12 // in the code :: (h % 12) + ap :: will return the correct hour value
真的没有更好的方法来做到这一点。 必须分别获取日期/月份/年份并再次组合在一起。 http://jsfiddle.net/uoghb0v3/
var oldDate = '2021-03-10';
var convertDate = new Date(oldDate);
var newDate = (convertDate.getMonth()+1) + '-' + convertDate.getDate() + '-' + convertDate.getFullYear();
var b = '7:45 AM';
var newB = newDate + " " + b;
var bDate = new Date(newB).getTime();
console.log(bDate);
output: 1615333500000
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.