Date in variable reading as "Invalid Date" - javascript

Using the following:
var timestart = $('.thisDiv').data("timestart");
var startDateTime = new Date(timestart);
to collect a date from a php file that is updating by ajax from this:
$TimeStart = date( 'Y,m,d,g,i', $TimeStart );
<div class="thisDiv" data-timestart="<?= $TimeStart ?>"></div>
var timestart = $('.thisDiv').data("timestart");
In console I'm getting the following when logging timestart and startDateTime:
2017,07,24,7,50
Invalid Date
If I paste the date that is output as follows
var startDateTime = new Date(2017,07,24,7,50);
Then it works fine. Any ideas why I'm getting Invalid Date?

Your timestart variable (JavaScript) is just a string. So it's a string 2017,07,24,7,50, and not those elements in order - which can't be used as separate parameters like new Date() expects.
Let's take a look at it!
var startDateTime = new Date(2017,07,24,7,50); // Parameters in order - all OK!
var startDateTime = new Date("2017,07,24,7,50"); // A single string - single parameter, not OK!
You need to return a proper format of dates from PHP with a format that's valid in JavaScript. Per the ECMAScript standard, the valid format that should work across all browsers is YYYY-MM-DDTHH:mm:ss.sssZ (see the reference at the bottom). To define that from PHP, you would need to format it as such
$TimeStart = date('c', $TimeStart);
This would return a format such as 2017-07-24T21:08:32+02:00.
Alternatively, you can use a splat/spread-operator ... and split the string it into elements, which I find as the better approach than above.
var timestart = $('.thisDiv').data("timestart"); // Get the string: "2017,07,24,7,50"
timestart = timestart.split(","); // Split into array
var startDateTime = new Date(...timestart); // Pass as arguments with splat-operator
Spread/splat operator in JavaScript
PHP date() documentation
ECMAScript date string (JavaScript)

You need to convert your date from string format to numbers.
var timestart = $('.thisDiv').data("timestart").split(",").map(Number);
var startDateTime = new Date(...timestart);
console.log(startDateTime)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="thisDiv" data-timestart="2017,07,24,7,50"></div>

Related

Google forms to calendar event issues with date format

So I have a very simple form that takes 3 inputs, a title, start and end date. I have tried to use a simple script to produce a calendar event. this can be seen below.
function onFormSubmit(e) {
var title = e.values[1];
var start_time = new Date(e.values[2]);
var end_time = new Date(e.values[3]);
CalendarApp.createEvent(title, start_time, end_time);
}
The issue I have is that as the date string is UK format (e.g. 05/12/2016 12:00:00) it is logging the events as 12th May as opposed to 5th December.
I am new to all of this so am looking for an elegant and simple solution I understand, not just to copy code I don't.
Thanks.
function convertUKDateToUSDate(date) {
const arr = date.split('/');
const temp = arr[0];
arr[0] = arr[1];
arr[1] = temp;
return arr.join('/');
}
will convert a date string with the prefix "DD/MM/" into "MM/DD/YYYY" format. Split turns the string into an array like ["DD", "MM", "YYYY HH:MM:SS"] and then the temporary variable is used to swap the "MM" and "DD" before the array entries are joined back together with the same character that was used to split them. You'll end up with a final onFormSubmit(e) like this:
function onFormSubmit(e) {
var title = e.values[1];
var start_time = new Date(convertUKDateToUSDate(e.values[2]));
var end_time = new Date(convertUKDateToUSDate(e.values[3]));
CalendarApp.createEvent(title, start_time, end_time);
}
Obviously I'm assuming e.values[2] and e.values[3] are strings. If they're Date objects already (or if you just want a shorter solution), then consider using the Moment.js (the premier Date object library) format function to convert between the formats. Normally I'd recommend using Moment anyways but you said you wanted something you could understand instead of copy.

Getting "Invalid Date" when passing dynamic date in IE 11 only in Javascript

Creating date using dynamically generated date string throws invalid date message only in IE11.
Example
var today = new Date();
var ag_endDate = new Date(today).toLocaleDateString('en-US');
var final = new Date(ag_endDate);
console.log(final);
try this
var dateObj = new Date();
var usFormatDate = dateObj.toLocaleDateString('en-US');
console.log( usFormatDate );
sorry, my bad! date constructor does take date Object as parameter.
However, if your intention is to simply get the formatted date in en-US locale, then you don't have to create another date object for the same.

Javascript convert dates

I am getting this "20131218" date/time value from an API result.
What I want to do is convert this date into something like this "2013-12-18". I know this is very easy in PHP by simply doing this code:
echo date("Y-m-d",strtotime('20131218'));
output: 2013-12-18
This is what I tried in javascript:
var myDate = new Date("20131218");
console.log(myDate);
But the output is Date{ Invalid Date } so obviously this is wrong.
My question here what is the equivalent of strtotime in javascript? or if there's no equivalent, how would I convert this value as my expected result(2013-12-18) using javascript?
Your help will be greatly appreciated!
Thanks! :)
The value is invalid to convert it to date. So either from your PHP code send it as a proper format like 20131218
Or convert the value you get in your Javascript to similar kind of format.
var dateVal="20131218";
/*
// If it's number ******* //
var numdate=20131218;
var dateVal=numdate.toString();
*/
var year=dateVal.substring(0,4);
var mnth=dateVal.substring(4,6);
var day=dateVal.substring(6,8);
var dateString=year+"-"+mnth+"-"+day;
var actualDate = new Date(dateString);
alert(actualDate);
JSFIDDLE DEMO
Javascript has a Date.parse method but the string you have is not suitable to pass to it. You don't really need to create a date object just to format a string. Consider:
function formatDateStr(s) {
s = s.match(/\d\d/g);
return s[0] + s[1] + '-' + s[2] + '-' + s[3];
}
alert(formatDateStr('20131218')); // '2013-12-18'
If you wish to convert it to a date object, then:
function parseDateStr(s) {
s = s.match(/\d\d/g);
return new Date(s[0] + s[1], --s[2], s[3]);
}
The reason why it is showing Invalid date is, it wants it to be in format
Following format: YYYY-MM-DD or YYYY-MM-DDTHH:MM:SS
If you breakdown your string using following format just add dash at relevant places then you are good to go and use newDate.
1. var myDate = new Date("2013-12-18");
alert(myDate);
2. var myDate = new Date(2013,12,18);
Eventually you can modify your string manipulate it and use it in aforementioned format.

How to get time difference between two date time in javascript?

I want time duration between two date time. I have the start date, start time, end date and end time. Now I have to find the difference between them.
Actually I have tried with this following code, but I got the alert like 'invalidate date'.
function myfunction()
{
var start_dt = '2013-10-29 10:10:00';
var end_dt = '2013-10-30 10:10:00';
var new_st_dt=new Date(start_dt);
var new_end_dt=new Date(end_dt);
alert('new_st_dt:'+new_st_dt);
alert('new_end_dt:'+new_end_dt);
var duration=new_end_dt - new_st_dt;
alert('duration:'+duration);
}
the alert msg like as follows:
new_st_dt:invalid date
new_end_dt: invalid date
duration:NaN
when I run in android simulator I got these alert messages.
Please help me how to get it? How to implement this?
You're passing an invalid ISO date string to that Date() constructor. It needs a form like
YYYY-MM-DDThh:mm:ss
for instance
2013-10-29T10:10:00
So you basically forgot the T to separate date and time. But even if the browser reads in the ISO string now, you would not have an unix timestamp to calculate with. You either can call
Date.parse( '2013-10-29T10:10:00' ); // returns a timestamp
or you need to explicitly parse the Date object, like
var duration=(+new_end_dt) - (+new_st_dt);
Further read: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse
Try formatting you timestamps as isoformat so javascript recognizes them. (you put a "T" between the date and time). An example: '2013-10-29T10:10:00'
function dateDiff(){
var start_dt = '2013-10-29 10:10:00';
var end_dt = '2013-10-30 10:10:00';
var d1= start_dt ;
d1.split("-");
var d2= end_dt ;
d2.split("-");
var t1 = new Date(d2[0],d2[1],d2[2]);
var t2 = new Date(d1[0],d1[1],d1[2]);
var dif = t1.getTime() - t2.getTime();
var Seconds_from_T1_to_T2 = dif / 1000;
return Math.abs(Seconds_from_T1_to_T2);
}

Passing value to new Date giving Invalid date

When i pass value to new Date then i get Invalid date. I am doing it like
var s1 = moment("20.06.2013 09:11:00", "DD.MM.YYYY HH:mm:ss");
var s2 = s1.format("YYYY.MM.DD HH:mm:ss");
var dt1 = s2.replace(/[-,.:\s]/g, ",");
var dt2 = new Date(dt1);
In Debug mode in google chrome when i get value of dt1 as "2013,06,20,09,11,00". But when i type like new Date(2013,06,20,09,11,34) then i get date.
I also tried removing double quotes but it doesnt remove double quotes. What should i do to get rid of this error.
If you are after a Date, but want to parse using moment.js, then just do this:
var m = moment("20.06.2013 09:11:00", "DD.MM.YYYY HH:mm:ss");
var dt = m.toDate();
As Kalley suggested, use parameters in your code:
var s1 = moment([2013,06,20,09,11,34]);
Edited to add: In Jscript, moment() takes an array in the format [Y,M,D,h,m,s]. Source: http://momentjs.com/docs/

Categories

Resources