how to compare the date in xml row with today's date - javascript

I have one xml file which is retrieved using jquery in sharepoint. One of the row of the xml is like below.
<z:row ows_Title='Have dinner party with Host' ows_Due_x0020_Date='2012-05-10 00:00:00' ows_MetaInfo='1;#' ows__ModerationStatus='0' ows__Level='1' ows_ID='1' ows_UniqueId='1;#{2A8F277A-C95B-420C-89A9-3B979F95C8F4}' ows_owshiddenversion='3' ows_FSObjType='1;#0' ows_Created='2012-10-25 03:19:35' ows_PermMask='0x7fffffffffffffff' ows_Modified='2012-10-29 00:56:09' ows_FileRef='1;#personal/Inclusions/Lists/Events/1_.000' />
Now i want to retireve the "Due Date" column and compare with the today's date. For retrieving date there is no issue. But how to compare the both dates? For comparing the date with today I used like this.
var k = new Date();
var year = k.getYear();
var month = k.getMonth();
var day = k.getDate();
var fulldate = year+"-"+month+"-"+day
But it is displaying only with date. In xml we are getting time also. I dont want to compare with time. I want to compare with only dates. How to achieve it? I want to put that whole process in the following function.
$(xData.responseXML).find("z\\:row").each(function() {
//here i want to compare that date column with present date
});
Finally i want, the date coming in the xml is less than the today's date or not?

Something like this:
function isPastDate( date ) {
return (new Date( date )).getTime() < (new Date()).getTime();
}

Highly recommend Date.js library for all the comparison and formatting methods that can make a lot of date work greatly simplified
http://www.datejs.com/

finally the required comparison like below.
function compareDates(passdate)
{
var splitdate = passdate.split(" ");
var splitdate1 = splitdate[0].split("-");
var newdate = splitdate1[1]+"-"+ splitdate1[2]+"-"+splitdate1[0];
return ((Date.parse(newdate)) < (new Date()).getTime());
}

Related

If 7 or more days past html date and if not paid change the innerHTML using only vanilla JS

If I have the following hard coded HTML date:
<h2 id="date">17/02/2018</h2>
<h2 id="status">Not paid</h2>
With a deadline being the h2 date plus 1 week or more.
How would I write javascript so that if the deadline is gone and the h2 status is not paid then how would I change the <h2 id="status">Not paid</h2>
to display the text overdue instead of Not paid
I tried getting the current date then adding 7 days by using moment.js:
moment().format('L').add(7, 'days'); since it gives me the same date format (dd/mm/yyyy) then comparing it to the h2 date but the problem is since moment.js will always get today's date and add 7 days to it so it will always be 7 days in the future. Not 7 days from the h2 date.
A seemingly simple problem which I have been stuck with for 2 days.
You need to get access to the date first, by pulling the text from the date element:
let myDate = document.getElementById('date').innerText;
Then, you can use moment to instantiate that as a moment date (assuming it's in a valid format):
let momentDate = moment(myDate, "DD/MM/YYYY");
Now you can work with momentDate by adding days to it, comparing it to other dates, etc., e.g.:
let oneWeekLater = momentDate.add(7, 'days');
If you want to change the value of the "status" element, you can then do something like:
let statusElement = document.getElementById("status");
statusElement.innerText = "Thank you for paying!";
Heres the solution:
const currentStatus = document.getElementById('status').innerText;
let myDate = document.getElementById('date').innerText;
//get the date in the html
// 100% correct
let momentDate = moment(myDate, "DD/MM/YYYY");
// gets the myDate variable and converts it into soemthing JS can understand
// 100% correct
let oneWeekLater = momentDate.add(7, 'days').format("YYYY/MM/DD");
// Need to comapare the dates based on bigest number first which is the year then
month etc... it then adds one week on to it
let today = moment(new Date()).format("YYYY/MM/DD");
// prints out todays date in the same format as oneWeekLater so they cna be compared
if(currentStatus.innerText == "Up-paid"){
if (oneWeekLater >= today){
document.write('Overdue')
} else{
document.write('not paid')
}
} else {
currentStatus.innerText = "Thank you for paying"
}

Reading the date from textbox as a string and converting it into as Date

I am reading the date from textbox by using javascript and trying to convert it as Date object.But my problem is date is converting as month and month is converting as date when converting the string to date.
Example:
03/12/2014 the value in the textbox
Actual Output:
03 as March,
12 as date (Its wrong)
Expected Output:
03 as date
12 as December (I am expecting)
While converting this string to date by using following snippet
var startTime = document.getElementById("meeting:startTime");
date.js
var stringToDate_startTime=new Date(Date.parse(startTime.value,"dd/mm/yy"));
moment.js
var date1=moment(startTime.value).format('DD-MM-YYYY');
In the above even i have used date.js and moment.js files also.But those also did not solve my problem.Please can anyone help me out to get rid out of this.
Try ...
var from = startTime.value.split("/");
var newDate = newDate(from[2], from[1] - 1, from[0]);
... assuming time included ...
var date_only = startTime.value.split("");
var from = date_only[0].split("/");
var newDate = newDate(from[2], from[1] - 1, from[0]);
I am not aware of an implementation of the Date.parse() method that accepts two arguments. You can view the Mozilla Date.parse() method description here Date.parse() - JavaScript | MDN.
It might be worth looking at the question/answer of this question for some more information: Why does Date.parse give incorrect results?
The next best option would be to split the date using String.split() and to rearrange the date parts
var dateStr = '03/12/2014 23:05';
var newDateStr = null;
var dateParts = dateStr.split('/');
if (dateParts.length == 3) {
var day = dateParts[0];
var month = dateParts[1];
var yearAndTime = dateParts[2];
// Rearrange the month and day and rejoin the date "12/03/2014 23:05"
newDateStr = [ month, day, yearAndTime].join('/');
} else {
throw new Error('Date not in the expected format.');
}
var date = new Date(newDateStr); // JS Engine will parse the string automagically
alert(date);
This isn't the most elegant solution, but hopefully that helps.

Parsing a date in JavaScript?

Is there a way I could get the year, month (0 based) and day from '03/05/2013'
If so, how?
Thanks
Is there a safe way to do it that can check if it is in the correct format?
You have the Date.parse method which parses a Date string and returns its timestamp, so you can call new Date().
Something like this:
new Date(Date.parse('03/06/2013'))
Most easy is using the split() function, i think:
var date = "03/05/2013";
var dateParts = date.split("/");
var day = dateParts[0];
var month = dateParts[1];
var year = dateParts[2];
http://jsfiddle.net/s7ma2/1/

how can change the text string to date object?

i am getting string from server and i need to covert that fetching string in to new date object.. for doing this, i tried this function, but no use, any one can help me to convert strings to date object?
my code is :
var nationZone = {
getNewYorkLocalTime : 'getTime.php?lat=40.71417&lan=74.00639',
getLondonLocalTime : 'getTime.php?lat=51.5&lan=0.1166667',
getChennaiLocalTime : 'getTime.php?lat=13.0833333&lan=80.2833333',
getBangaloreLocalTime:'getTime.php?lat=12.9833333&lan=77.5833333'
}
$.each(nationZone , function(key, value){
$.get(value, function(response){
var newdate = $(response).find('localtime').text();
if(key == "getNewYorkLocalTime"){
var newyourktime = new Date(newdate);
newyourktime.getTime()
}
});
});
but, the newyourktime is showing local time only.. any help please? as well i am getting the response from server is : 17 Nov 2011 18:09:47 - like this.
Use http://www.datejs.com/
As an example:
var newyourktime = Date.parse('2011-11-11, 11:11 AM');
alert(newyourktime.toString('dd/mm/yyyy HH:mm:ss EST'));
Check out the Datejs library documentation to meet your requirements, after your date string is parsed, you can do a lot with it.
This will try to parse the date using the client machine own local settings, which is not good.
Instead of passing it as string, pass it as the total seconds that passed since 1/1/1970 at midnight and use this number when constructing the new Date object of JavaScript.
For example pass this number: 1321614000000 and you will get November 18th 2011, 1 PM
You could use substr
day = newdate.substr(0,2);
month = newdate.substr(3,3);
year = newdate.substr(7,4);
var newyorktime = new Date(year, month, day);
Substr

How to check if input date is equal to today's date?

I have a form input with an id of 'date_trans'. The format for that date input (which is validated server side) can be any of:
dd/mm/yyyy
dd-mm-yyyy
yyyy-mm-dd
yyyy/mm/dd
However, before posting the form, I'd like to check if the date_trans field has a date that is equal to today's date. Its ok if the date taken is the client's date (i.e. it uses js), since I run a double check on the server as well.
I'm totally lost on how to do the date comparrison in jQuery or just plain old javascript. If it helps, I am using the jquery datepicker
A simple date comparison in pure JS should be sufficient:
// Create date from input value
var inputDate = new Date("11/21/2011");
// Get today's date
var todaysDate = new Date();
// call setHours to take the time out of the comparison
if(inputDate.setHours(0,0,0,0) == todaysDate.setHours(0,0,0,0)) {
// Date equals today's date
}
Here's a working JSFiddle.
for completeness, taken from this solution:
You could use toDateString:
var today = new Date();
var isToday = (today.toDateString() == otherDate.toDateString());
no library dependencies, and looking cleaner than the 'setHours()' approach shown in a previous answer, imho
Try using moment.js
moment('dd/mm/yyyy').isSame(Date.now(), 'day');
You can replace 'day' string with 'year, month, minute' if you want.
function sameDay( d1, d2 ){
return d1.getUTCFullYear() == d2.getUTCFullYear() &&
d1.getUTCMonth() == d2.getUTCMonth() &&
d1.getUTCDate() == d2.getUTCDate();
}
if (sameDay( new Date(userString), new Date)){
// ...
}
Using the UTC* methods ensures that two equivalent days in different timezones matching the same global day are the same. (Not necessary if you're parsing both dates directly, but a good thing to think about.)
Just use the following code in your javaScript:
if(new Date(hireDate).getTime() > new Date().getTime())
{
//Date greater than today's date
}
Change the condition according to your requirement.Here is one link for comparision compare in java script
The following solution compares the timestamp integer divided by the values of hours, minutes, seconds, millis.
var reducedToDay = function(date){return ~~(date.getTime()/(1000*60*60*24));};
return reducedToDay(date1) == reducedToDay(date2)
The tilde truncs the division result (see this article about integer division)
Date.js is a handy library for manipulating and formatting dates. It can help in this situation.
Try this
// method to check date is less than today date
isLessDate(schedule_date : any){
var _schedule_date = new Date(schedule_date);
var date = new Date();
var transformDate = this.datePipe.transform(date, 'yyyy-MM-dd');
var _today_date = new Date(''+transformDate);
if(_schedule_date < _today_date){
return 'small'
}
else if(_schedule_date > _today_date){
return 'big'
}
else {
return 'same'
}
}
The Best way and recommended way of comparing date in typescript is:
var today = new Date().getTime();
var reqDateVar = new Date(somedate).getTime();
if(today === reqDateVar){
// NOW
} else {
// Some other time
}
TodayDate = new Date();
if (TodayDate > AnotherDate) {} else{}
< = also works, Although with =, it might have to match the milliseconds.
There is a simpler solution
if (inputDate.getDate() === todayDate.getDate()) {
// do stuff
}
like that you don't loose the time attached to inputDate if any

Categories