JS中将日期时间分别转换为日期和时间格式

目前我的日历有这个 html


<!--Grid column-->

<div class="col-md-6">

<div class="md-form mb-0">

    <input placeholder="Selected date" data-toggle="datepicker" type="text" id="myDate" name="myDate" class="form-control datepicker">

    <label for="myDate" id="dateLabel">Estimated Start Date</label>

</div>

</div>

 <!--Grid column-->

目前我有这个


var est_start_date = $(this).attr('data-esd');


以及我使用此代码将其放入文本框的值


$('#myDate').val(est_start_date);


其中包含这样的值

http://img3.mukewang.com/61a86a82000135e702170053.jpg

正如您所注意到的,数据还包括时间

如何将日期时间格式化为这样的 MM/DD/YYYY

http://img.mukewang.com/61a86a92000188b201940059.jpg

也将时间分隔为这种格式

http://img.mukewang.com/61a86a9b00013d9b01460045.jpg



一只斗牛犬
浏览 329回答 3
3回答

UYOU

让日期=新日期(document.querySelector('#myDate').value)日期部分 ===> date.toLocaleDateString() 。时间部分 ====> date.toLocaleTimeString() 用于时间部分。

扬帆大鱼

使用它来将您的日期转换为所需的格式,&nbsp; function formatDate(date) {&nbsp; &nbsp; date = date.split(" ");&nbsp; &nbsp; let dateOne = date[0];&nbsp; &nbsp; let time = date[1];&nbsp; &nbsp; time = time.split(":");&nbsp; &nbsp; time.forEach((val,index)=>{&nbsp; &nbsp; &nbsp; if(val.length <2){&nbsp; &nbsp; &nbsp; &nbsp; val = "0" + val;&nbsp; &nbsp; &nbsp; &nbsp; time[index] = val;&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; })&nbsp; &nbsp; time = time.join(":");&nbsp; &nbsp; let str = `${dateOne}T${time}.000Z`;&nbsp; &nbsp; let offset = (new Date()).getTimezoneOffset()*60*1000;&nbsp; &nbsp; date = new Date( (new Date(`${dateOne}T${time}.000Z`)).getTime() + offset);&nbsp; &nbsp; const arr = [date.getMonth() + 1, date.getDate(), date.getFullYear()]&nbsp; &nbsp; var hours = date.getHours();&nbsp; &nbsp; var minutes = date.getMinutes();&nbsp; &nbsp; var ampm = hours >= 12 ? 'PM' : 'AM';&nbsp; &nbsp; hours = hours % 12;&nbsp; &nbsp; hours = hours ? hours : 12; // the hour '0' should be '12'&nbsp; &nbsp; minutes = minutes < 10 ? '0'+minutes : minutes;&nbsp; &nbsp; var strTime = hours + ':' + minutes + ' ' + ampm;&nbsp; &nbsp; var date = arr.join("/");&nbsp; &nbsp; return date + " " +strTime;&nbsp; }&nbsp;&nbsp; let date = '2019-10-21 1:41:00';&nbsp; console.log(formatDate(date));

缥缈止盈

您可以使用 javascript 日期对象来获取所需的格式。用这个,function formatDate(date) {const arr = [date.getMonth() + 1, date.getDate(), date.getFullYear()]&nbsp; var hours = date.getHours();&nbsp; var minutes = date.getMinutes();&nbsp; var ampm = hours >= 12 ? 'PM' : 'AM';&nbsp; hours = hours % 12;&nbsp; hours = hours ? hours : 12; // the hour '0' should be '12'&nbsp; minutes = minutes < 10 ? '0'+minutes : minutes;&nbsp; var strTime = hours + ':' + minutes + ' ' + ampm;&nbsp; var date = arr.join("/");&nbsp; return date + " " +strTime;}console.log(formatDate(new Date));
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript