简体   繁体   English

在javascript中将日期转换为其他格式

[英]Convert date to other format in javascript

I am getting a date and a time from 2 input boxes with datebox plugin. 我从2个带有datebox插件的输入框中获取日期和时间。

I have the date as "16-01-2015" and time as "11:37 AM". 我的日期为“16-01-2015”,时间为“11:37 AM”。 I need to send both to my server to add to the database but my database need the date in format: "2015-01-16 21:11:00" 我需要发送到我的服务器添加到数据库,但我的数据库需要格式的日期:“2015-01-16 21:11:00”

How can I convert my both strings in a date or a string with the other format? 如何将日期或字符串中的两个字符串转换为其他格式? I also need to convert 12 hour time to 24h time. 我还需要将12小时时间转换为24小时。

Using moment.js : 使用moment.js

var dateInitial = "16-01-2015";
var timeInitial = "11:37 AM";

//Parse the date as String to Moment
var dateAsMoment = moment(dateInitial + " " + timeInitial, 'DD-MM-YYYY HH:mm A');

//Parse the date as Moment to String in the desired format
var dateToSend = dateAsMoment.format('YYYY-MM-DD HH:mm:ss')

http://jsfiddle.net/vcarvalho/w240pfz6/2/ http://jsfiddle.net/vcarvalho/w240pfz6/2/

// You can reverse the numbers in the date and adjust the hours as needed. //您可以反转日期中的数字并根据需要调整小时数。

function parsedaytime(inputday, inputtime){
    var dstr= inputday.value.split('-').reverse().join('-'), 
    tstr= inputtime.value.split(/:| /), 
    ampm= tstr.pop();

    if(ampm== 'PM' && tstr[0]!== '12') tstr[0]-=-12;
    return '"'+dstr+' '+tstr.join(':')+'"';
}

var inputday={value: "16-01-2015"}, inputtime={value: "11:37 PM"}; var inputday = {value:“16-01-2015”},inputtime = {value:“11:37 PM”}; parsedaytime(inputday,inputtime) parsedaytime(inputday,inputtime)

returned value: (String) "2015-01-16 23:37" 返回值:(String)“2015-01-16 23:37”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM