NaN javascript error when calculating between dates with timestamp - javascript

I would like to begin by saying i looked at multiple threads in this forum before posting. Wasnt able to find my solution :(
Issue: getting a NaN error when trying to find the difference between two dates with a timestamp from two textboxes.
The date format i'm using is DDMMYYYY HH:MM - 27/01/2015 00:00
code below.
thank you in advance for this super helpful forum :)
function stringToDate(s) {
var dateParts = s.split(' ')[0].split('-');
var timeParts = s.split(' ')[1].split(':');
var d = new Date(dateParts[0], --dateParts[1], dateParts[2]);
d.setHours(timeParts[0], timeParts[1], timeParts[2]);
return d;
}
function test() {
var a = textbox_1.value;
var b = textbox_2.value;
alert(stringToDate(a) - stringToDate(b));
}

Your date has / as separator but you are splitting the string on -. Change
var dateParts = s.split(' ')[0].split('-');
to
var dateParts = s.split(' ')[0].split('/');
Also, your time part has only hours and minutes, so there is no timeParts[2] present, just remove it from the setHours() call. Like this:
d.setHours(timeParts[0], timeParts[1])
Fiddle: http://jsfiddle.net/2evj59d1/
EDIT
Your code returns the difference in milliseconds. To convert it into date format just change
alert(stringToDate(a) - stringToDate(b));
to
alert(new Date(stringToDate(a) - stringToDate(b)));

The code is trying to parse a time in the format HH:MM:SS. Skip the third part:
d.setHours(timeParts[0], timeParts[1]);

You can convert the date into milliseconds, get the difference and get the date back.
Fiddle
JSCode:
var a = new Date();
a.setDate(15);
a = a.getTime();
var b = new Date();
b.setDate(32);
b = b.getTime();
var c = b - a;
var date = new Date(c);
alert(date.getDate() - 1);

for those who may have stumbled upon my post, i found my answer at the link below by user benjour.
How do I get the difference between two Dates in JavaScript?

Related

Change format date in JavaScript

I want to change the format in JavaScript, to be Year-month-day
I used this code to get 3 months before, but the format that was generated became like this 9/19/2019.
This my code:
var d = new Date();
d.setMonth(d.getMonth() - 3);
var x = d.toLocaleDateString();
console.log(x);
You can get Year, Month and Date and use string interpolation like below
var d = new Date();
d.setMonth(d.getMonth() - 3);
var formattedDate = `${d.getFullYear()}-${(d.getMonth() + 1)}-${d.getDate()}`;
console.log(formattedDate);
You can use momentjs, a lightweight and handy library for this purpose:
var d = moment(new Date()).subtract(3, 'months').format('dd-MMM-yyyy);
var x = d.toISOString().substring(0,10);
console.log(x);
//it will give you the format of y-m-d
You are using the toLocaleDateString() which will format to the result you received which is expected.
Reference Mozilla's Docs on Date() to get the right function for you there :)
Most instances you are able to just piece it together yourself similar to:
const date = `${date.getYear()}/${date.getMonth()}/${date.getDay()}`;
It's not a nice solution but there are a lot of restrictions with OOTB Date()

Formatting dates when getting days between 2 dates with JQuery/Javascript

I am trying to calculate the days between 2 dates and it is working as far as I can tell but I keep getting stupidly high numbers which clearly isn't right, I have a feeling this is the way my dates are set out. my dates are set out as dd/mm/yyyy and this is the code I am using:
var diff = new Date(end_date - start_date);
var days = diff/1000/60/60/24;
console.log("diff=>"+days);
This is the question I used to get the answer:
JavaScript date difference Days
When it writes to the console this is the result I get:
diff=>17301.95833332176
I have had a play with the code, although I have not used HTML, i set the vars statically below.
var end_date = new Date("May 25, 2017");
var start_date = new Date("May 23, 2017");
var diff = new Date(end_date - start_date);
var days = diff/1000/60/60/24;
console.log("diff=>"+days);
I have also checked it with a 3 value date format
var end_date = new Date(2017,4,25);
var start_date = new Date(2017,4,23);
var diff = new Date(end_date - start_date);
var days = diff/1000/60/60/24;
console.log("diff=>"+days);
I manage to get an output of 2. Which is what i expected. The code you supplied looks ok to me. Maybe look at the HTML to check that the values being passed are in the correct format.
Jquery datepicker may be of help to you here.
You could also use moment: https://momentjs.com
var moment = require('moment');
var start_moment = moment(start_date);
var end_moment = moment(end_date);
var days = start_moment.diff(end_moment, 'days');
console.log("diff=>" + days);
You can also get weeks, months etc. with this method
Easy solution, is to use countBtw
var { date } = require('aleppo')
//..
date.countBtw('all', date1, date2)

Convert SQL datetime to string or Date object [duplicate]

How can I convert a string to a date time object in javascript by specifying a format string?
I am looking for something like:
var dateTime = convertToDateTime("23.11.2009 12:34:56", "dd.MM.yyyy HH:mm:ss");
Use new Date(dateString) if your string is compatible with Date.parse(). If your format is incompatible (I think it is), you have to parse the string yourself (should be easy with regular expressions) and create a new Date object with explicit values for year, month, date, hour, minute and second.
I think this can help you: http://www.mattkruse.com/javascript/date/
There's a getDateFromFormat() function that you can tweak a little to solve your problem.
Update: there's an updated version of the samples available at javascripttoolbox.com
#Christoph Mentions using a regex to tackle the problem. Here's what I'm using:
var dateString = "2010-08-09 01:02:03";
var reggie = /(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/;
var dateArray = reggie.exec(dateString);
var dateObject = new Date(
(+dateArray[1]),
(+dateArray[2])-1, // Careful, month starts at 0!
(+dateArray[3]),
(+dateArray[4]),
(+dateArray[5]),
(+dateArray[6])
);
It's by no means intelligent, just configure the regex and new Date(blah) to suit your needs.
Edit: Maybe a bit more understandable in ES6 using destructuring:
let dateString = "2010-08-09 01:02:03"
, reggie = /(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/
, [, year, month, day, hours, minutes, seconds] = reggie.exec(dateString)
, dateObject = new Date(year, month-1, day, hours, minutes, seconds);
But in all honesty these days I reach for something like Moment
No sophisticated date/time formatting routines exist in JavaScript.
You will have to use an external library for formatted date output, "JavaScript Date Format" from Flagrant Badassery looks very promising.
For the input conversion, several suggestions have been made already. :)
Check out Moment.js. It is a modern and powerful library that makes up for JavaScript's woeful Date functions (or lack thereof).
Just for an updated answer here, there's a good js lib at http://www.datejs.com/
Datejs is an open source JavaScript Date library for parsing, formatting and processing.
var temp1 = "";
var temp2 = "";
var str1 = fd;
var str2 = td;
var dt1 = str1.substring(0,2);
var dt2 = str2.substring(0,2);
var mon1 = str1.substring(3,5);
var mon2 = str2.substring(3,5);
var yr1 = str1.substring(6,10);
var yr2 = str2.substring(6,10);
temp1 = mon1 + "/" + dt1 + "/" + yr1;
temp2 = mon2 + "/" + dt2 + "/" + yr2;
var cfd = Date.parse(temp1);
var ctd = Date.parse(temp2);
var date1 = new Date(cfd);
var date2 = new Date(ctd);
if(date1 > date2) {
alert("FROM DATE SHOULD BE MORE THAN TO DATE");
}
time = "2017-01-18T17:02:09.000+05:30"
t = new Date(time)
hr = ("0" + t.getHours()).slice(-2);
min = ("0" + t.getMinutes()).slice(-2);
sec = ("0" + t.getSeconds()).slice(-2);
t.getFullYear()+"-"+t.getMonth()+1+"-"+t.getDate()+" "+hr+":"+min+":"+sec
External library is an overkill for parsing one or two dates, so I made my own function using Oli's and Christoph's solutions. Here in central Europe we rarely use aything but the OP's format, so this should be enough for simple apps used here.
function ParseDate(dateString) {
//dd.mm.yyyy, or dd.mm.yy
var dateArr = dateString.split(".");
if (dateArr.length == 1) {
return null; //wrong format
}
//parse time after the year - separated by space
var spacePos = dateArr[2].indexOf(" ");
if(spacePos > 1) {
var timeString = dateArr[2].substr(spacePos + 1);
var timeArr = timeString.split(":");
dateArr[2] = dateArr[2].substr(0, spacePos);
if (timeArr.length == 2) {
//minutes only
return new Date(parseInt(dateArr[2]), parseInt(dateArr[1]-1), parseInt(dateArr[0]), parseInt(timeArr[0]), parseInt(timeArr[1]));
} else {
//including seconds
return new Date(parseInt(dateArr[2]), parseInt(dateArr[1]-1), parseInt(dateArr[0]), parseInt(timeArr[0]), parseInt(timeArr[1]), parseInt(timeArr[2]))
}
} else {
//gotcha at months - January is at 0, not 1 as one would expect
return new Date(parseInt(dateArr[2]), parseInt(dateArr[1] - 1), parseInt(dateArr[0]));
}
}
Date.parse() is fairly intelligent but I can't guarantee that format will parse correctly.
If it doesn't, you'd have to find something to bridge the two. Your example is pretty simple (being purely numbers) so a touch of REGEX (or even string.split() -- might be faster) paired with some parseInt() will allow you to quickly make a date.
Just to give my 5 cents.
My date format is dd.mm.yyyy (UK format) and none of the above examples were working for me. All the parsers were considering mm as day and dd as month.
I've found this library: http://joey.mazzarelli.com/2008/11/25/easy-date-parsing-with-javascript/
and it worked, because you can say the order of the fields like this:
>>console.log(new Date(Date.fromString('09.05.2012', {order: 'DMY'})));
Wed May 09 2012 00:00:00 GMT+0300 (EEST)
I hope that helps someone.
Moment.js will handle this:
var momentDate = moment('23.11.2009 12:34:56', 'DD.MM.YYYY HH:mm:ss');
var date = momentDate.;
You can use the moment.js library for this. I am using only to get time-specific output but you can select what kind of format you want to select.
Reference:
1. moment library: https://momentjs.com/
2. time and date specific functions: https://timestamp.online/article/how-to-convert-timestamp-to-datetime-in-javascript
convertDate(date) {
var momentDate = moment(date).format('hh : mm A');
return momentDate;
}
and you can call this method like:
this.convertDate('2020-05-01T10:31:18.837Z');
I hope it helps. Enjoy coding.
To fully satisfy the Date.parse convert string to format dd-mm-YYYY as specified in RFC822,
if you use yyyy-mm-dd parse may do a mistakes.
//Here pdate is the string date time
var date1=GetDate(pdate);
function GetDate(a){
var dateString = a.substr(6);
var currentTime = new Date(parseInt(dateString ));
var month =("0"+ (currentTime.getMonth() + 1)).slice(-2);
var day =("0"+ currentTime.getDate()).slice(-2);
var year = currentTime.getFullYear();
var date = day + "/" + month + "/" + year;
return date;
}

How to get the Australian Time Zone using Javascript? (Not JQuery)

I am trying to help a friend to get the Australian Time Zone for the University Assignment and finding difficulty.
Could someone point us in the right direction?
Thank you!
<script>
function Timezone() {
var x = new Date();
var currentTimeZoneOffsetInHours = x.getTimezoneOffset() / 60;
document.getElementById("add").innerHTML = currentTimeZoneOffsetInHours;
}
</script>
<p id="add"></p>
You simply use
let AuDate = new Date().toLocaleString("en-US", {timeZone: "Australia/Sydney"});
By looking at your code, looks like you are trying to get the current date and time of an Australian timezone. Lets say you want Australian Eastern Standard Time (AEST) and you want the date displayed how they would in Australia DD-MM-YYYY then do the following:
var timestamp_UTC = new Date();
var readable_timestamp_AEST = timestamp_UTC.toLocaleDateString("en-AU", {timeZone: "Australia/Sydney"}).replace(/\//g, "-") + ' ' + somestamp.toLocaleTimeString("en-AU", {timeZone: "Australia/Sydney"});
"en-AU" is the locales argument which tells the toLocalDateString to display the date as DD-MM-YYYY and the second argument is for options (timeZone is just one such possible option). Info about toLocalDateString function can be found here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString
Here is some information about the Date() function https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
Hope this clears up a few things around getting times and dates from the Date() function.
I think i understand what you mean. But before that i'd like to make 2 points:
1: The Timezone() function should be called somewhere.
<script>
function Timezone() {
var x = new Date();
var currentTimeZoneOffsetInHours = x.getTimezoneOffset() / 60;
document.getElementById("add").innerHTML = currentTimeZoneOffsetInHours;
}
Timezone();
</script>
2: The convention usually is that methods start with a lower case letter. Maybe updateTimezone() would be more appropriate.
Your question can be interpreted in 2 ways now:
you want your timezone's offset in hours and for this the code above should work. getTimezoneOffset() is the way to go.
you want a human readable name of your timezone, as you can see on my site currentmillis.com (in my case it says GTB Summer). You can look in my source code to see how i achieve this:
var s = date.toString();
var iOfP = s.indexOf('('); // index of parenthesis
if (iOfP < 0) {
s = s.substring(s.lastIndexOf(' ') + 1);
} else {
s = s.substring(iOfP+1, s.length-1);
}
if (s.length > 4 && s.lastIndexOf(" Time") == s.length-5){
s = s.substring(0, s.length-5);
}
timezoneM.innerHTML = s;
This works because when you call toString() on the date the result should contain the full name of your timezone: w3schools.com/jsref/jsref_tostring_date.asp

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);
}

Categories

Resources