Javascript: check formatted date value against current date? - javascript

a text-input contains a german formatted date 15.09.2012
I simply use $('#wr_event_date').val() to query the value in the input-field.
I wonder how I can match that date agains "today"?
var eventDate = $('#wr_event_date').val();
// if eventDate is older than today as in "is over" doSomething();
So basically I want to check if the eventDate is older than today and if so I want to doSomething();
Ideas on that? Thank you in advance.

Unfortunately, you have to parse the date yourself. Then, fetch the current date with new Date(), reset the time part, and compare both dates:
var s = $('#wr_event_date').val().split(".");
var eventDate = new Date(s[2], s[1] - 1, s[0]);
var today = new Date();
today.setHours(0, 0, 0, 0); // reset time
if (eventDate.getTime() - today.getTime() < 0) { // event date is older than today
doSomething();
}
DEMO.

If you could use a third party library, then moment.js provides the functions to parse date strings and manipulate dates.

var parts = '15.09.2012'.split('.')
var date = Date.parse(parts[1], parts[0] - 1, parts[2]);
if (date - new Date().getTime() > 24 * 60 * 60 * 1000) ...
​

Related

Stop date to epoch conversion in javascript

I have a code where I try to set date 20 days back from current date on server. I have used a variable(say dateRange) in javascript to get current date. But on using the same variable second time for setDate() function value of dateRange is changed to epoch from date. I know I can convert epoch to date and proceed but is there a way to stop this automatic conversion.
var dateRange=new Date(currentDate);
dateRange = dateRange.setDate(dateRange.getDate() - 20);
setDate modifies the date object, and returns the epoch value. Just don't save the epoch value in dateRange, so you can use the date object after modifying it:
var currentDate = new Date();
var dateRange = new Date(+currentDate);
console.log(dateRange.toISOString());
dateRange.setDate(dateRange.getDate() - 20);
console.log(dateRange.toISOString());
Side note: Copying a date by doing var dateRange = new Date(currentDate); is/was unreliable on some browsers. In the above, I've changed it to var dateRange = new Date(+currentDate); (note the +, converting the date to its epoch value), which is reliable.
Internally dates are stored as milliseconds from the epoch date.
To achieve what you are trying to do you can subtract the number of milliseconds that corresponds to 20 days:
var currentDate = "2019-07-29T07:14:57.269Z";
var dateRange = new Date(currentDate);
var pastDate = new Date(dateRange - 1000 * 60 * 60 * 24 * 20);
console.log('current', currentDate);
console.log('20 days ago', pastDate);
anyway if you are doing a lot of date/time manipulations in your app i suggest you to use this library: https://momentjs.com/

Javascript/jQuery decrementing an input date with datepicker [duplicate]

I need to decrement a Javascript date by 1 day, so that it rolls back across months/years correctly. That is, if I have a date of 'Today', I want to get the date for 'Yesterday'.
It always seems to take more code than necessary when I do this, so I'm wondering if there's any simpler way.
What's the simplest way of doing this?
[Edit: Just to avoid confusion in an answer below, this is a JavaScript question, not a Java one.]
var d = new Date();
d.setDate(d.getDate() - 1);
console.log(d);
var today = new Date();
var yesterday = new Date().setDate(today.getDate() -1);
day.setDate(day.getDate() -1); //will be wrong
this will return wrong day. under UTC -03:00, check for
var d = new Date(2014,9,19);
d.setDate(d.getDate()-1);// will return Oct 17
Better use:
var n = day.getTime();
n -= 86400000;
day = new Date(n); //works fine for everything
getDate()-1 should do the trick
Quick example:
var day = new Date( "January 1 2008" );
day.setDate(day.getDate() -1);
alert(day);
origDate = new Date();
decrementedDate = new Date(origDate.getTime() - (86400 * 1000));
console.log(decrementedDate);
setDate(dayValue)
dayValue is an integer from 1 to 31, representing the day of the month.
from https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Date/setDate
The behaviour solving your problem (and mine) seems to be out of specification range.
What seems to be needed are addDate(), addMonth(), addYear() ... functions.
Working with dates in JS can be a headache. So the simplest way is to use moment.js for any date operations.
To subtract one day:
const date = moment().subtract(1, 'day')

javascript - compare dates in different formats

I have 2 dates which I need to compare to see if one is greater than the other but they are in different formats and I'm not sure of the best way to compare the 2.
The formats are:
1381308375118 (this is var futureDate)
which is created by
var today = new Date(); today.setHours(0, 0, 0, 0); var futureDate = new Date().setDate(today.getDate() + 56); //56 days in the future...
And the other format is
2013/08/26
Any ideas how I can compare the 2?
Without using a 3rd party library, you can create new Date objects using both those formats, retrieve the number of milliseconds (since midnight Jan 1, 1970) using getTime() and then simply use >:
new Date("2013/08/26").getTime() > new Date(1381308375118).getTime()
I strongly recommend using datejs library.
Thus this can be written in one single line:
Date.today().isAfter(Date.parse('2013/08/26'))
I would make sure that I am comparing the "date" element of each format and exclude any "time" element. Then with both dates converted to milliseconds, simply compare the values. You could do something like this. If dates are equal it returns 0, if the first date is less that the second then return -1, otherwise return 1.
Javascript
function compareDates(milliSeconds, dateString) {
var year,
month,
day,
tempDate1,
tempDate2,
parts;
tempDate1 = new Date(milliSeconds);
year = tempDate1.getFullYear();
month = tempDate1.getDate();
day = tempDate1.getDay();
tempDate1 = new Date(year, month, day).getTime();
parts = dateString.split("/");
tempDate2 = new Date(parts[0], parts[1] - 1, parts[2]).getTime();
if (tempDate1 === tempDate2) {
return 0;
}
if (tempDate1 < tempDate2) {
return -1;
}
return 1;
}
var format1 = 1381308375118,
format2 = "2013/08/26";
console.log(compareDates(format1, format2));
On jsfiddle
Maybe you can use Date.parse("2013/08/26") and compare with former one
Follow these steps to compare dates
Each of your date must to passed through Date object i.e. new Date(yourDate).
Now dates will have same format and these will be comparable
let date1 = new Date()
let date2 = "Jan 1, 2019"
console.log(`Date 1: ${date1}`)
console.log(`Date 2: ${date2}`)
let first_date = new Date(date1)
let second_date = new Date(date2)
// pass each of the date to 'new Date(yourDate)'
// and get the similar format dates
console.log(`first Date: ${first_date}`)
console.log(`second Date: ${second_date}`)
// now these dates are comparable
if(first_date > second_date) {
console.log(`${date2} has been passed`)
}

convert iso date to milliseconds in javascript

Can I convert iso date to milliseconds?
for example I want to convert this iso
2012-02-10T13:19:11+0000
to milliseconds.
Because I want to compare current date from the created date. And created date is an iso date.
Try this
var date = new Date("11/21/1987 16:00:00"); // some mock date
var milliseconds = date.getTime();
// This will return you the number of milliseconds
// elapsed from January 1, 1970
// if your date is less than that date, the value will be negative
console.log(milliseconds);
EDIT
You've provided an ISO date. It is also accepted by the constructor of the Date object
var myDate = new Date("2012-02-10T13:19:11+0000");
var result = myDate.getTime();
console.log(result);
Edit
The best I've found is to get rid of the offset manually.
var myDate = new Date("2012-02-10T13:19:11+0000");
var offset = myDate.getTimezoneOffset() * 60 * 1000;
var withOffset = myDate.getTime();
var withoutOffset = withOffset - offset;
console.log(withOffset);
console.log(withoutOffset);
Seems working. As far as problems with converting ISO string into the Date object you may refer to the links provided.
EDIT
Fixed the bug with incorrect conversion to milliseconds according to Prasad19sara's comment.
A shorthand of the previous solutions is
var myDate = +new Date("2012-02-10T13:19:11+0000");
It does an on the fly type conversion and directly outputs date in millisecond format.
Another way is also using parse method of Date util which only outputs EPOCH time in milliseconds.
var myDate = Date.parse("2012-02-10T13:19:11+0000");
Another option as of 2017 is to use Date.parse(). MDN's documentation points out, however, that it is unreliable prior to ES5.
var date = new Date(); // today's date and time in ISO format
var myDate = Date.parse(date);
See the fiddle for more details.
Yes, you can do this in a single line
let ms = Date.parse('2019-05-15 07:11:10.673Z');
console.log(ms);//1557904270673
Another possible solution is to compare current date with January 1, 1970, you can get January 1, 1970 by new Date(0);
var date = new Date();
var myDate= date - new Date(0);
Another solution could be to use Number object parser like this:
let result = Number(new Date("2012-02-10T13:19:11+0000"));
let resultWithGetTime = (new Date("2012-02-10T13:19:11+0000")).getTime();
console.log(result);
console.log(resultWithGetTime);
This converts to milliseconds just like getTime() on Date object
var date = new Date()
console.log(" Date in MS last three digit = "+ date.getMilliseconds())
console.log(" MS = "+ Date.now())
Using this we can get date in milliseconds
var date = new Date(date_string);
var milliseconds = date.getTime();
This worked for me!
if wants to convert UTC date to milliseconds
syntax : Date.UTC(year, month, ?day, ?hours, ?min, ?sec, ?milisec);
e.g :
date_in_mili = Date.UTC(2020, 07, 03, 03, 40, 40, 40);
console.log('miliseconds', date_in_mili);
In case if anyone wants to grab only the Time from a ISO Date, following will be helpful. I was searching for that and I couldn't find a question for it. So in case some one sees will be helpful.
let isoDate = '2020-09-28T15:27:15+05:30';
let result = isoDate.match(/\d\d:\d\d/);
console.log(result[0]);
The output will be the only the time from isoDate which is,
15:27

creating date from a timestring in javascript

I am new to javascript and am trying to compare two date values ,I am getting two time value strings in the format
06:30:47 AM
01:10:47 PM
I need to compare these to find out if the first one is less than the other.I couldn't figure out how to do this in javascript.Can someone help?
o.h
I do not think that the standard implementation can parse this. I would do something like this:
function toDate(dateString) {
var timeComponents = dateString.replace(/\s.*$/, '').split(':');
if (dateString.indexOf("PM") > -1) {
timeComponents[0] += 12;
}
var date = new Date();
date.setHours(timeComponents[0]);
date.setMinutes(timeComponents[1]);
date.setSeconds(timeComponents[2]);
return date;
}
if (toDate('06:30:47 AM') > toDate('01:10:47 PM')) {
// ...
}
JavaScript's specified date/time parsing, what you can rely upon cross-browser, is surprisingly limited. For a long time, there was no single string date format that was mandated in the spec, and as of the recent 5th edition spec, the only mandated format is ISO-8601 (and some subsets). You can't yet rely on browsers having implemented that part of the 5th edition spec.
So you have a couple of choices:
Parse the string yourself and use the Date constructor that takes the individual parts of the date as numbers, e.g. new Date(year, month, day, hour, minute, second, ...). (You need only specify as many of those as you want, so for instance new Date(2010, 9, 14) is September 14th, 2010.)
Use a library like Moment that's already done the work for you. Moment lets you specify the format to parse.
Use the Date object. Check this: http://www.w3schools.com/jsref/jsref_obj_date.asp
Try putting the two values in Date variables and do this:
if(var1.valueOf() > var2.valueOf())
{
//Do Something
}
If your times are always in the format 00:00:00 AM then
var a="06:30:47 AM";
var b="01:10:47 PM";
var at=parseInt(a.substring(0,8).replace(/(^0+|:)/g,""));
var bt=parseInt(b.substring(0,8).replace(/(^0+|:)/g,""));
if (a.charAt(9)=="P") {at=at+120000};
if (b.charAt(9)=="P") {bt=bt+120000};
if (at<bt) {
// a is smaller
}
else
{
// a is not smaller
};
..should be cross-browser and time/format safe.
I tried something like this
var ts1="06:30:47 AM";
var ts2="01:10:47 PM";
var ds=new Date().toDateString();
var d1=new Date(ds+" "+ts1);
var d2=new Date(ds+" "+ts2);
if (!(d2>d1)){
alert("d1 should be less than d2");
}
Is there something wrong with this?
// specific formatter for the time format ##:##:## #M
var formatToMiliseconds = function(t){
t = t.split(/[:\s]/);
t = ((t[0] * 3600000) + (t[1] * 60000) * (t[2] * 1000)); // To ms
t = t + (/PM/i.test(t[3]) ? 43200000 : 0); // adjust for AM/PM
return t;
}
var time01 = formatToMiliseconds('06:30:47 AM');
var time02 = formatToMiliseconds('01:10:47 PM');
alert(time01 > time02); // false
allert(time01 < time02); // true
As a bonus, your time is now more compatible with the Date object and other time calculations.

Categories

Resources