1

I am getting a date and a time from 2 input boxes with datebox plugin.

I have the date as "16-01-2015" and time as "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"

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.

Biribu
  • 3,615
  • 13
  • 43
  • 79
  • 1
    Take a look in this library: [http://momentjs.com/](http://momentjs.com/) – Victor Jan 15 '15 at 15:10
  • 2
    possible duplicate of [Where can I find documentation on formatting a date in JavaScript](http://stackoverflow.com/questions/1056728/where-can-i-find-documentation-on-formatting-a-date-in-javascript) – Hacketo Jan 15 '15 at 15:11
  • I tried but I always get Date {Invalid Date} whenever I try to print moment(date + " "+ time) or just date or just time – Biribu Jan 15 '15 at 15:12

2 Answers2

3

Using 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/

Victor
  • 5,043
  • 3
  • 41
  • 55
0

// 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"}; parsedaytime(inputday,inputtime)

returned value: (String) "2015-01-16 23:37"

kennebec
  • 102,654
  • 32
  • 106
  • 127