JavaScript/jQuery datetime difference - javascript

I am trying to identify whether given date-time is future date and time or not.
For e.g. My current date time is '25-04-2010 08:26 PM' and if I pass '25-04-2010 09:00 PM' to a JavaScript function, then it should return me '1' if that date-time is future date & time otherwise it should return me '0'.

I decided to do this using timestamp. So I just wrote below code.
var myDate = new Date("April 25, 2011 21:16:00"); // Your timezone!
var myEpoch = myDate.getTime()/1000.0;
document.write(myEpoch);
var cur_date = new Date(); // Current date
var myEpoch1 = cur_date.getTime()/1000.0;
document.write("---"+myEpoch1);
var diff=myEpoch-myEpoch1; // If diff comes minus value, then it is past date-time, otherwise it is future data-time
alert(diff);
thanks.

var myDate=new Date();
myDate.setFullYear(2010,0,14);
var today = new Date();
if (myDate>today)
{
alert("Today is before 14th January 2010");
}
else
{
alert("Today is after 14th January 2010");
}
source: link

This seems like a simple parsing job to me. I won't give you the code, but will give you the approach.
Use split to split the string on ' ' (empty space)
Use split to split the first string [0] on '-'
Use split to split the second string [1] on ':'
-- Now simply concatenate all the strings in the order yyyymmddhhmmss
so your time string will become a signature like : 201004250900
and the second one becomes : 201003250826
Now simply do an integer compare ;)
This is the long winded approach
It just occurred to me that you should be able to parse the time string you're passing to date in javascript, and that makes your life easier... Try that.

Related

Issues parsing a string-date React/JS

For example, I have this string "2020-09-09T21:00:14.114-04:00"
I grab this from my database and in its current form, it is a string. my goal is to have it display
4 PM instead of the long string of jibberish
is it possible to accomplish this?
I was thinking of possibly creating a new date object like
let test = new Date('2020-09-09T21:00:14.114-04:00').
but I'm stuck at the parsing and formatting part. it would be better to have this be done while the current state is a string but I don't think that this would be possible
edit: i would like the desired output to be the hour:minute and then am/pm
ex 10:15pm
You can do that by parsing the date from your database using Date.parse().
Then you can get the time or whatever you need using date.toLocalTimeString() in your case.
let dateUnix = Date.parse('2020-09-09T21:00:14.114-04:00');
const time = new Date(dateUnix).toLocaleTimeString();
console.log(time); // --> "4:00:14 AM"
The Date.parse() method parses a string representation of a date, and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC or NaN if the string is unrecognized or, in some cases, contains illegal date values (e.g. 2015-02-31).
Here's some useful resources MDN Date.parse()
MDN Date.toLocalTimeString()
You can do as following way.new Date() is used to get the current date and time.
var today = new Date();
var time = today.getHours();
if(time>12){
var new_time= time % 12;
}
else{
var new_time= time;
}

JavaScript getting date string as 11pm on the day before

I have the following input field:
In my web app I have -
string date - 06/05/2018
And this JS code:
var d = "06/05/2018".split("/");
var date = new Date(d[2] + "-" + d[1] + "/" + d[0]).getTime();
console.log(date)
This returns 1525561200000 which if I put that into epoch converter gives me...
Saturday, May 5, 2018 11:00:00 PM
This then screws up with my filtering system - date ranges because if I select the minimum date to be 06/05/2018 with the input field:
var d = $('#min').val()
var date = new Date(d).getTime();
console.log(date)
It is returning 1525564800000 which comes to Sunday, May 6, 2018 12:00:00 AM
How do I get around this?
Thanks
I could write an entire thesis on how problematic and difficult it is to work with dates in Javascript and how to avoid pitfalls and weird bugs, but in the end your specific problem comes down to a simple typo.
The string you're parsing manually and passing to the Date constructor looks like this:
2018-05/06
You've mistakenly used a / instead of a - as the second delimiter when concatenating the string. For some reason, the browser then creates the date object as midnight 2018-05-06 local time. When passing in the string in the standard format (which is what happens when taking it from the date input), i.e. 2018-05-06, the date object gets created as midnight 2018-05-06 UTC time.
So, in short, your problem can be solved by replacing the "/" with "-" in your string concatenation and the two dates should be the same.
However, I should point out that passing a string to the Date constructor is unreliable since the result is not standardized and may differ between browsers (which is also why it behaves so unpredictable and seemingly illogical in this case). It's a better idea to pass numbers instead since the specification dictates the result of that. You're already halfway there since you've split the date string into its components. Try this:
var date = new Date(
Number(d[2]),
Number(d[1]) - 1, // Subtracting 1 from month since it's base 0
Number(d[0])
).getTime();
(Technically, we don't even need to explicitly convert to Number since the Date constructor expects all arguments to be numbers when there's more than one argument and will convert whatever it gets into numbers internally)

Create now/subtract dates/month with format of "2014-08-04T17:19:00-07:00" in JavaScript

How do I create the time now and format it to a string with format of "2014-08-04T17:19:00-07:00"? Using moment.js or any other JavaScript?
I will also need to create 2 new, one to subtract a week from now, one to subtract a month from now, but also with this format.
Simply enough:
var d = Date.now(); //For current time in MS
d = new Date(); //For current time wrapped in the object.
d.toISOString();
For more on ISO String read this or that.
If you want to do any Date arithmetic, like adding a month, just add/subtract the number of milliseconds for that unit to your date object.
Additionally, if you don't want time in Zulu, you can use String manipulation to drop the Z and add the proper zone. Don't forget to account for the difference in time zones!
You can do this:
var date = new Date();
date.toISOString();
> "2014-08-05T17:22:08.030Z"
// Subtract one week:
var before = date;
before.setDate(date.getDate()-7);
before.toISOString();
> "2014-07-29T17:22:08.030Z"

Comparing today's date with another date in moment is returning the wrong date, why?

I'm using moment.js 1.7.0 to try and compare today's date with another date but the diff function is saying they are 1 day apart for some reason.
code:
var releaseDate = moment("2012-09-25");
var now = moment(); //Today is 2012-09-25, same as releaseDate
console.log("RELEASE: " + releaseDate.format("YYYY-MM-DD"));
console.log("NOW: " + now.format("YYYY-MM-DD"));
console.log("DIFF: " + now.diff(releaseDate, 'days'));
console:
RELEASE: 2012-09-25
NOW: 2012-09-25
DIFF: 1
Ideas?
Based on the documentation (and brief testing), moment.js creates wrappers around date objects. The statement:
var now = moment();
creates a "moment" object that at its heart has a new Date object created as if by new Date(), so hours, minutes and seconds will be set to the current time.
The statement:
var releaseDate = moment("2012-09-25");
creates a moment object that at its heart has a new Date object created as if by new Date(2012, 8, 25) where the hours, minutes and seconds will all be set to zero for the local time zone.
moment.diff returns a value based on a the rounded difference in ms between the two dates. To see the full value, pass true as the third parameter:
now.diff(releaseDate, 'days', true)
------------------------------^
So it will depend on the time of day when the code is run and the local time zone whether now.diff(releaseDate, 'days') is zero or one, even when run on the same local date.
If you want to compare just dates, then use:
var now = moment().startOf('day');
which will set the time to 00:00:00 in the local time zone.
RobG's answer is correct for the question, so this answer is just for those searching how to compare dates in momentjs.
I attempted to use startOf('day') like mentioned above:
var compare = moment(dateA).startOf('day') === moment(dateB).startOf('day');
This did not work for me.
I had to use isSame:
var compare = moment(dateA).isSame(dateB, 'day');

Why can't I create a Date from a string including milliseconds?

In javascript you can create a Date object from a string, like
var mydate = new Date('2008/05/10 12:08:20');
console.log(mydate); //=> Sat May 10 2008 12:08:20 GMT+0200
Now try this using milliseconds in the string
var mydate = new Date('2008/05/10 12:08:20:551'); // or '2008/05/10 12:08:20.551'
console.log(mydate); //=> NaN
Just out of curiosity: why is this?
EDIT: thanks for your answers, which all offer sufficient explanation. Maybe in some future there will be support for use of milliseconds in date strings. Untill then I cooked up this, which may be of use to somebody:
function dateFromStringWithMilliSeconds(datestr){
var dat = datestr.split(' ')
,timepart = dat[1].split(/:|\./)
,datestr = dat[0]+' '+timepart.slice(0,3).join(':')
,ms = timepart[timepart.length-1] || 0
,date;
date = new Date(datestr);
date.setMilliseconds(ms);
return date;
}
If you know the different components you can use this overload to the Date constructor:
var mydate = new Date(2008,6,10,12,8,20,551);
Note 6 for the month, as the months go from 0-11.
If needed you can take the string representation and split it to its component parts and pass those through to this constructor:
var datestring = '2008/05/10 12:08:20:551';
var datearray = datestring.split(/\s|:|\//g)
var mydate = new Date(datearray[0], parseInt(datearray[1]) + 1 , datearray[2], datearray[3],datearray[4],datearray[5],datearray[6]);
As described in this document, the string overload should conform to RFC-1123 (which in turn conforms to RFC-822) which does not support milliseconds.
dateString
String value representing a date. The string should be in a format recognized by the parse method (IETF-compliant RFC 1123 timestamps).
This format doesn't seem to accommodate milliseconds in the date... It may be best to just define the date without ms and then call setMilliseconds() afterwards.
The ECMA-262 standard, section 15.9.1.15, does indeed specify milliseconds in the date string format. I'm guessing the browser developers just couldn't be bothered to implement it.

Categories