"invalid date" in javascript when making a date out of Date().getTime() - javascript

I have the following Javascript code:
var dateMilliseconds = web3.toAscii(newArray[i]).substring(0, 13)
console.log(dateMilliseconds) // returns 1500282374082
var date = new Date(dateMilliseconds)
console.log(date) // returns invalid date
If I try var date = new Date(1500282374082) instead, it works - how should I be passing the dateMilliseconds variable in properly and what type should it be?

You need to pass this as an integer, and not a string.
You can use the +value trick to convert it into an integer:
var date = new Date(+dateMilliseconds)

Related

Angular 6: Invalid time value

I am trying to get two date and times as a string of numbers (epoch) so I can compare them. One is a new Date():
today = new Date().valueOf();
And one is from an api response in the format:
scheduleDate: "2019-07-22T00:00+01:00"
The issue is I am trying to get the returned date in the correct format. When I try
var scheduleDate = new Date(scheduleDate).toISOString()
console.log("converted date:" + scheduleDate);
I get the error:
Invalid time value
How do I get the returned date into epoch format?
Thanks
Your scheduleDate variable must be undefined. Are you sure it's being assigned properly?
(function() {
//number (milleseconds)
const today = new Date().valueOf();
//string
const scheduleDate = undefined; //"2019-07-22T00:00+01:00";
const scheduleDate2 = new Date(scheduleDate).toISOString()
console.log(typeof today);
console.log(typeof scheduleDate);
console.log("converted date: " + scheduleDate);
}
)();
More worryingly, why are you converting a date string to a date and then back to a string (same value).
You are missed to assign the value
scheduleDate= "2019-07-22T00:00+01:00"
Then try its working
> scheduleDate= "2019-07-22T00:00+01:00"
'2019-07-22T00:00+01:00'
> new Date(scheduleDate)
2019-07-21T23:00:00.000Z
> var scheduleDate = new Date(scheduleDate).toISOString()
undefined
> scheduleDate
'2019-07-21T23:00:00.000Z'
> console.log("converted date:" + scheduleDate);
converted date:2019-07-21T23:00:00.000Z

Date in variable reading as "Invalid Date"

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>

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.

Date validation failing

I wish to check whether a one given date is less than the other date using JavaScript + jQuery.
However, when checking a date that is one day less than the given date, the condition is not met.
This is my code;
$('#payment_date').change(function(){
payment_date_1 = String($("#payment_date").val());
s_date_1 = String($("#s_date").text());
payment_date = new Date(payment_date_1);
s_date = new Date(s_date_1);
if(payment_date<s_date){
alert("please enter a correct date");
$("#payment_date").val("");
}
});
ex: when s_date == '2013-07-02' and payment_date == '2013-07-01' the condition is returning false rather than true.
My HTML:
<span style="display:none;" id="s_date">2013-07-02</span>
<input type="text" value="" name="payment_data_info[payment_date]" id="payment_date" class="hasDatepicker" readonly="readonly">
Note; I have checked if both dates are valid, two dates are returning valid dates and the condition is working perfectly well for other instances
I just found out why; I'm using jQuery's date picker. Dates less than and equal to 2013-07-10 returns a valid date and dates less than 2013-07-10 and larger than 2013-06-30 returns an invalid date. Any idea why?
First of all check if variable declaration is the problem, than check if the string parsing returns the dates you're expecting. Maybe s_date and payment_date are invalid after all?
I expierenced difficulties too with the direct comparison (don't know why), so I used the valueOf-function to get values for comparison.
Sure it works ;)
http://jsfiddle.net/4MQkK/
payment_date_1 = "2013-07-01";
s_date_1 = "2013-07-02";
payment_date = new Date(payment_date_1);
s_date = new Date(s_date_1);
if(payment_date < s_date){
alert(payment_date + "is lower than " + s_date);
}
Check your values of payment_date_1 and s_date_1 at least one of them could not be parsed correctly
Try this , I hope it will help.
$('#payment_date').change(function(){
var payment_date_1 = $("#payment_date").val(); //add var
var s_date_1 = $("#s_date").text(); //add var
var payment_date = new Date(payment_date_1);
var s_date = new Date(s_date_1);
if((payment_date.valueOf())<(s_date.valueOf())){
alert("please enter a correct date");
$("#payment_date").val("");
}
});
2 Possible Causes:
1) Where Date is called as a constructor with more than one argument,
if values are greater than their logical range (e.g. 13 is provided as the month value or 70 for the minute value), the adjacent value will be adjusted. E.g. new Date(2013,13,1) is equivalent to new Date(2014,1,1),
(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date)
your date format is 'dd/MM/yyyy' but new Date () use format yyyy/dd/mm so 2013-06-30: 30 is month i.e. 30 month more then 06/01/2013 --> 06/06/2015
you need to change the format. for example:
var myDate = "2013/01/30"
var split= myDate .split("/");
new Date (split[2],split[1],split[0]);
2) months in Date() in javascript they numeric 0-11. so 01/03/2013 changed to 01/04/2013
int month = myMonth -1; // for example: mymonth = 'March' => month = 2
can use new Date(2013,month,30);
You can do something like this.
var payment_date_1 = $("#payment_date").val();
var s_date_1 = $("#s_date").text(); or $("#s_date").val();
// IF s_date_1 is a input field then you have to use .val()
For typecast String. You can do
var payment_date_1 = $("#payment_date").val().toString();
var s_date_1 = $("#s_date").val().toString();
PLease create date objects and then check
var first = new Date($("#s_date").text());
var second = new Date($("#s_date_1").text());
if(first.getTime() < second.getTime()) {
// code
}

Categories

Resources