Page 1 of 1

Create valid date from string

Posted: Mon Mar 17, 2014 11:23 am
by Joe Bohen

Hi,

I need to create a valid date time from a string in order to use the created date as a parameter in a database request; My string is in the British date time format '18/03/2014 08:57' and I have attempted to convert this into a usable parameter with the following code but I get an invalid date exception. How do I do this correctly?

var sStr = ('18/03/2014 08:57').split(' ');
var timeStr=(sStr[1] + '.000');
var datePart = sStr[0].split('/');
var dayStr = datePart[0];
var mthStr= datePart[1];
var yearStr = datePart[2];
var utcDate = yearStr + '-' + mthStr + '-' + ' ' + dayStr + timeStr;
var D = new Date(utcDate);
console.log(D);


Create valid date from string

Posted: Mon Mar 17, 2014 12:29 pm
by Joe Bohen

Ok so I have a valid date returned and I am writing this to a date field in the Appery database when I try to query this record with the query string:

{"enddate":{"$gt":{"$date":"2014-04-18 11:22:00.000"}}}

I get an error!

the date builder:

var sStr = Appery('eDate_txt').val().split(' ');
var timeStr=sStr[1].split(':');
var datePart = sStr[0].split('/');
var hrsStr = timeStr[0];
var minStr = timeStr[1];
var dayStr = datePart[0];
var mthStr= datePart[1];
var yearStr = datePart[2];

var d = new Date(yearStr, mthStr, dayStr, hrsStr, minStr, '00', '00');

return d.toISOString();


Create valid date from string

Posted: Mon Mar 17, 2014 1:35 pm
by Nikita

Hello,

Let's try code like this:

var sStr = Appery('eDate_txt').val();
var d = new Date(sStr.replace(/(\d+)-(\d+)-(\d+)/, '$2/$3/$1'));
return d.toISOString().replace("T"," ").replace("Z","");


Create valid date from string

Posted: Mon Mar 17, 2014 1:44 pm
by Joe Bohen

Hello Nikita, This code causes the original error: 'Uncaught RangeError: Invalid time value '


Create valid date from string

Posted: Mon Mar 17, 2014 2:28 pm
by Nikita

Sorry. Let's correct this code a little:

var sStr = Appery('eDate_txt').val();
var s = sStr.replace(/(\d+)\/(\d+)\/(\d+)/, '$2-$1-$3');
var d = new Date(s);
return d.toISOString().replace("T"," ").replace("Z","");

It must work.


Create valid date from string

Posted: Mon Mar 17, 2014 3:00 pm
by Joe Bohen

Hi Nikita,

That has corrected the error when I write the record to the database, but when I attempt to query the record using these parameters I get a 500 error:

where:{ "registration" : "X1GBA", "enddate":{"$gte":{"$date":"2014-03-17 14:57:00.000"}}}

What is the correct method to query a record with a date value created using your code?

Thanks


Create valid date from string

Posted: Mon Mar 17, 2014 3:39 pm
by Nikita

Hi,

Let's try to change your code to this one:
where:{ "registration" : "X1GBA", "enddate":{"$gte":"2014-03-17 14:57:00.000"}}


Create valid date from string

Posted: Mon Mar 17, 2014 4:27 pm
by Joe Bohen

Hi Nikita, thats corrected the error thank you.