Ho to Parse STRING to Date/Time field?

hyperjam
Giga Contributor

Hello, i have an inbound email action to create a new records from emails.

The email body_test contains string date, presented in such way, for example - Thursday, July 14, 2016 11:00:43 PM

I'm extracting that date, and i need it to be inserted in the DATE/Time field [u_date] (so for example -   2016-07-14 23:00:43)

Do you have suggestion on how to do that?

Any input will be welcomed, because i'm lost with that

Thank you!

1 ACCEPTED SOLUTION

Oh wow, that is a lot of coding. If I am not wrong, this can be achieved in 4 lines


var sec=Date.parse("Thursday, July 14, 2016 11:00:43 PM");


var gdt = new GlideDateTime();


gdt.setNumericValue(sec);


gdt.getDisplayValue(); //this will give you the date in your format


View solution in original post

25 REPLIES 25

Abhinay Erra
Giga Sage

Here you go



var sec=Date.parse("Thursday, July 14, 2016 11:00:43 PM");


var gdt = new GlideDateTime();


gdt.setNumericValue(sec);


gdt.getDisplayValue(); //this will give you the date in your format


Chuck Tomasi
Tera Patron

Well that was fun... Here you go Anna. Remove or comment out the gs.print statements. I only use them for debugging.



var str = 'July 14, 2016 11:00:43 PM';



var part = str.split(' ');


var monthName = part[0];


var date = part[1].replace(/,/, '');


var year = part[2];


var time = part[3];


var ampm = part[4];



var dateStr = year + '-' + monthNumber(monthName) + '-' + date;


var timePart = time.split(':');


var hh = timePart[0];


var mm = timePart[1];


var ss = timePart[2];



var hour = parseInt(hh, 10);



if (hour == 12 && ampm == 'AM')


  hh = '00';



if (ampm == 'PM' && hour < 12) {


  hour += 12;


  hh = hour.toString();


}



timeStr = hh + ':' + mm + ':' + ss;


var newStr =   dateStr + ' ' + timeStr



gs.print('newStr=' + newStr);



var gdt = new GlideDateTime(newStr);


gs.print('gdt=' + gdt.getValue());



// current.u_date = gdt.getValue();



function monthNumber(name) {


  var monthList = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];


  for (var i = 0; i < monthList.length; i++) {



  if (name == monthList[i])


  return i + 1;


  }


}


Oh wow, that is a lot of coding. If I am not wrong, this can be achieved in 4 lines


var sec=Date.parse("Thursday, July 14, 2016 11:00:43 PM");


var gdt = new GlideDateTime();


gdt.setNumericValue(sec);


gdt.getDisplayValue(); //this will give you the date in your format


You win! I forgot about Date.parse().



Not the first (or last) time I have wasted time writing code for something that already existed.