JS - Compare which date is older - javascript

I want to compare two dates as which is bigger in those dates.
var date1 = 2011-9-2;
var date1 = 2011-17-06;
Can anybody say how can I do this?

You'll need to convert both strings to date objects first.
var date1 = new Date('2011-09-02');//yyyy-mm-dd format
var date2 = new Date('2011-06-17');
if(date1 > date2){
alert('date1 is bigger than date2');
}
Once you have the 2 variables as date objects you can compare them against each other (without needing to convert to milliseconds/minutes/?)

Check this link
And then do something like this:
var days = 0;
var difference = 0;
Christmas = new Date("December 25, 2005");
today = new Date();
difference = Christmas - today;
days = Math.round(difference/(1000*60*60*24));
Code source

Create Date objects from your two values (check this link) and use that to do the comparison.

Related

why are the dates not being generated properly?

I am using a function in Angular JS to generate the dates for the past one week starting from today's date. I am storing these dates in an array and then using that array to flood a dropdown.
The following is the code that is being used by me.
generate() {
this.date_new = [];
var date = new Date();
var date1 = new Date();
for (var i = 0; i < 7; i++) {
date.setDate(date1.getDate() - i);
var a = date.toString();
var str = this.convert(a);
this.date_new.push(str);
}
}
Here convert is a function which is being used to convert the dates to the required format. A screenshot of generated dates is attached below.
As evident from the screenshot, the last two dates are incorrect. Can somebody explain to me, what the problem is?
The setDate() method sets the day of the Date object relative to the
beginning of the currently set month.
The above is from MDN.
Your code works for the first 5 dates, but once you are modifying your February date with -1, it sets the day relative to the current month e.g. February. So this will turn into January (as you are setting the day to -1), same happens in the next iteration and you get December.
For an easy fix you can just set the date variable to new Date() in the first line of your for loop.
The issue here is using the same date variable in the loop. You need to re-initialize it.
As can be seen in Parameters Value section in the link here. Zero and negative values in setDate() sets the date from previous month.
Hence at setDate(0), date value is set to last day of Feb. Now since you are using the same variable, setDate(-1) takes the previous month from Feb hence you get Jan.
You need to change the code to something like this:
generate() {
this.date_new = [];
var date1 = new Date();
for (var i = 0; i < 7; i++) {
// re-initialize date
var date = new Date();
date.setDate(date1.getDate() - i);
var a = date.toString();
var str = this.convert(a);
this.date_new.push(str);
}
}
Hope this helps :)
The issue here is that negative numbers inside the setDate method don't work quite well.
Please update the code to something like below:
this.date_new = [];
var date = new Date();
var date1 = new Date();
for (var i = 0; i < 7; i++) {
date= new Date(date1.getFullYear(), date1.getMonth(),date1.getDate()-i);
var a = date.toString();
var str = this.convert(a);
this.date_new.push(str);
}
Hope this will solve your problem.

How to find the number of days difference using Google Script

I was trying to find the difference between two days, I'm getting NaN.
function formatDate(oldFormat,duration,timestamp){
var formattedDate = Utilities.formatDate(oldFormat, "IST","yyyy,MM,dd");
Logger.log(timestamp);
var newDate=new Date(timestamp*1000);
Logger.log(newDate);
newDate=Utilities.formatDate(newDate,"IST","yyyy,MM,dd");
Logger.log(formattedDate);
Logger.log(newDate);
var date1=new Date(formattedDate).getTime();
Logger.log(date1)
var date2=new Date(newDate).getTime();
Logger.log(date2)
var diff=daydiff(date2,date1);
Logger.log(diff); }
function daydiff(first, second) {
return (second-first)/(1000*60*60*24);}
How to find the difference between two date in days? I've date in this format :
date 1 : 2015,05,12
date 2: 2015,05,28
There is no point to use Utilities.formatDate() as it is meant to convert a normal date in to any format, not the other way round.
Also not sure what (oldFormat,duration,timestamp) stand for. You do not use duration in your script, and both dates you showed seem to be the same format.
If you are simply trying to find the difference between two dates, try this:
function formatDate(date1,date2){
date1 = new Date(fixDate(date1));
date2 = new Date(fixDate(date2));
var diff = (date2-date1)/(1000*60*60*24);
return(diff);
}
function fixDate(date){
var collector = date;
if (collector.match(",")!=null){
collector = collector.split(",");
var myString = [collector[1], collector[2], collector[0]].join("/");
return myString
}
}

How to Calculate Number of days between two calender dates which are in text format in Javascript?

I'm having a form which is having two input fields with date picker(with the help of jquery ui).One asking a check in date & the other asking check out date.I want to calculate the Number of Days Between those two dates.I am a beginner to javascript.So can any one help me?
Use unix timestamp. It's universal tool when you working with time:
var a = new Date(2012,11,10);
var b = new Date(2012,11,12);
var dt = (b.getTime() - a.getTime())/(24*3600*1000) //2
You must first get the value of such input fields, eg:
var v1 = document.getElementById('input1Id').value;
var v2 = document.getElementById('input2Id').value;
then you have to instantiate two new Javascript Date objects:
var parts1 = v1.split('/');
var parts2 = v2.split('/');
// this will split your string into date parts, eg. 11/30/2012 would result as an array ['11','30','2012'];
var date1 = new Date(parts1[2],parts1[0],parts1[1]);
var date2 = new Date(parts2[2],parts2[0],parts2[1]);
// remember to check the index of array items considering your date format
finally, you just have to subtract one date from the other to get the difference in days:
var difference = Math.Abs(date1 - date2);
difference = parseInt(difference / 86400000);
//86400000 are the milliseconds in one day. Parsing to int will round the day - eg.5,4 days results as 5 day
Edit: Sure, you can reference your html element by his id attribute
<input type="text" id="myTextbox">
---
var txb = document.getElementById('myTextbox');
// do anything else to your txb here, if u like
txb.value = difference;
that's it!

Parse string in given format to date

I want to parse date in the format ddMMyyhhmm (eg 2804121530 representing 28th April 2012, 3:30 PM) to javascript Date() object.
Is there any oneliner solution to it? I'm looking for something of the kind:
var date = Date.parse('2804121530', 'ddMMyyhhmm');
or
var date = new Date('2804121530', 'ddMMyyhhmm');
Thanks for help!
A useful library here is DateJs. Just add a reference:
<script src="http://datejs.googlecode.com/files/date.js"
type="text/javascript"></script>
and use Date.parseExact:
var dateStr = '2804121530';
var date = Date.parseExact(dateStr, 'ddMMyyHHmm');
For a fast solution you can brake that string into pieces and create date from those pieces
function myDateFormat(myDate){
var day = myDate[0]+''+myDate[1];
var month = parseInt(myDate[2]+''+myDate[3], 10) - 1;
var year = '20'+myDate[4]+''+myDate[5];
var hour = myDate[6]+''+myDate[7];
var minute = myDate[8]+''+myDate[9];
return new Date(year,month,day,hour,minute,0,0);
}
var myDate = myDateFormat('2804121530');
or a simper solution:
function myDateFormat(myDate){
return new Date(('20'+myDate.slice(4,6)),(parseInt(myDate.slice(2,4), 10)-1),myDate.slice(0,2),myDate.slice(6,8),myDate.slice(8,10),0,0);
}
var myDate = myDateFormat('2804121530');
(new Date(1381344723000)).toUTCString()
Correct me if 'm worng...

Javascript get date in format [duplicate]

This question already has answers here:
How do I format a date in JavaScript?
(68 answers)
Closed 3 years ago.
I want to get today's date in the format of mm-dd-yyyy
I am using var currentDate = new Date();
document.write(currentDate);
I can't figure out how to format it.
I saw the examples var currentTime = new Date(YY, mm, dd); and currentTime.format("mm/dd/YY");
Both of which don't work
I finally got a properly formatted date using
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1;//January is 0!`
var yyyy = today.getFullYear();
if(dd<10){dd='0'+dd}
if(mm<10){mm='0'+mm}
var today = mm+'/'+dd+'/'+yyyy;
document.write(today);'`
This seems very complex for such a simple task.
Is there a better way to get today's date in dd/mm/yyyy?
Unfortunately there is no better way, but instead of reinventing the wheel, you could use a library to deal with parsing and formatting dates: Datejs
<plug class="shameless">
Or, if you find format specifiers ugly and hard to decipher, here's a concise formatting implementation that allows you to use human-readable format specifiers (namely, the Date instance getters themselves):
date.format("{Month:2}-{Date:2}-{FullYear}"); // mm-dd-yyyy
</plug>
var today = new Date();
var strDate = 'Y-m-d'
.replace('Y', today.getFullYear())
.replace('m', today.getMonth()+1)
.replace('d', today.getDate());
Simple answer is no. Thats the only way to do it that I know of.
You can probably wrap into a function that you can reuse many times.
date.js is what you need. For example, snippet below is to convert a date to string as Java style
new Date().toString('M/d/yyyy')
function dateNow(splinter){
var set = new Date();
var getDate = set.getDate().toString();
if (getDate.length == 1){ //example if 1 change to 01
getDate = "0"+getDate;
}
var getMonth = (set.getMonth()+1).toString();
if (getMonth.length == 1){
getMonth = "0"+getMonth;
}
var getYear = set.getFullYear().toString();
var dateNow = getMonth +splinter+ getDate +splinter+ getYear; //today
return dateNow;
}
format this function is mm dd yyyy
and the dividing you can choice and replace if you want... for example
dateNow("/") you will get 12/12/2014
There is nothing built in, but consider using this if you are already using jQuery (and if not, then you should consider that as well!)
http://plugins.jquery.com/project/jquery-dateFormat
(new Date()).format("MM-dd-yyyy")
N.B. month is "MM" not "mm"
function appendZeros(value,digits){
var c= 1;
initValue = value;
for(i=0;i<digits-1;i++){
c = c*10;
if( initValue < c ){
value = '0' + value;
}
}
return value;
}

Categories