Multiple Date Object comparisons not working as expected - javascript

Trying to figure out why my Date Object values are not comparing correctly. The same 'GREATER than' string is being appended to both 'review-full-review-comment-wrap' blocks...Is my method of comparing the dateObjects values correct?
<div class="review-full-review-single-wrap">
<div class="review-full-stars">
<span class="review-full-timestamp">
<time itemprop="datePublished" datetime="2014-07-29T11:25:47-07:00">July 29, 2014</time>
</span>
</div>
<div class="review-full-review-comment-wrap"></div>
////*Append LESS THAN*////
</div>
<div class="review-full-review-single-wrap">
<div class="review-full-stars">
<span class="review-full-timestamp">
<time itemprop="datePublished" datetime="2015-05-05T05:50:05-07:00">May 5, 2015</time>
</span>
</div>
<div class="review-full-review-comment-wrap"></div>
////*Append GREATER THAN*////
</div>
function runProgram(){
var elems = document.getElementsByClassName("review-full-timestamp");
for (var i = 0; i < elems.length; i++) {
var timeElems = document.getElementsByTagName("time");
var dateString = Date.parse(timeElems[i].innerHTML);
var dateObj = new Date(dateString);
var startDate = "May 6, 2015";
var startDateObj = new Date(startDate);
}
if(dateObj > startDateObj){
$('.review-full-review-comment-wrap').append('<p>GREATER than</p>');
} else {
$('.review-full-review-comment-wrap').append('<p>LESS than</p>');
}
}
runProgram();

Based on the comment #Bergi made above: Here is the correct function
var startDate = new Date( 'May 6, 2015' );
$( '.review-full-review-single-wrap' ).each( function( i, e ) {
var dateObj = new Date( Date.parse( $( e ).find( '.review-full-timestamp > time' ).attr( 'dateTime' ) ) );
var div = $( e ).find( '.review-full-review-comment-wrap' );
if ( dateObj.getTime() >= startDate.getTime() ) {
div.append( '<p>dateObj is GREATER than startDate</p>' );
} else {
div.append( '<p>dateObj is LESS than startDate</p>' );
}
} );

See getTime()
Consider the following example based on your code:
var dateString = Date.parse('10-23-2015');
var dateObj = new Date(dateString);
var startDate = "May 6, 2015";
var startDateObj = new Date(startDate);
if(dateObj.getTime() > startDateObj.getTime()){
console.log('cool');
}
This outputs
cool
As you can see, 10-23-2015 is bigger than May 6, 2015.

Try adding .getTime() to each date object , push date values to an array , use Array.prototype.some() to determine if either of time elements html parsed to Date objects is greater than startDateObj
function runProgram() {
var times = [];
var startDate = "May 6, 2015";
var startDateObj = new Date(startDate).getTime();
var elems = document.getElementsByClassName("review-full-timestamp");
for (var i = 0; i < elems.length; i++) {
var timeElems = document.getElementsByTagName("time");
var dateString = Date.parse(timeElems[i].innerHTML);
var dateObj = new Date(dateString);
times.push(dateObj.getTime());
}
if (times.some(function(time) {
return time > startDateObj
})) {
$('.review-full-review-comment-wrap').append('<p>GREATER than</p>');
} else {
$('.review-full-review-comment-wrap').append('<p>LESS than</p>');
}
}
runProgram();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="review-full-review-single-wrap">
<div class="review-full-stars">
<span class="review-full-timestamp">
<time itemprop="datePublished" datetime="2014-07-29T11:25:47-07:00">July 29, 2014</time>
</span>
</div>
<div class="review-full-review-comment-wrap"></div>
////*Append LESS THAN*////
</div>
<div class="review-full-review-single-wrap">
<div class="review-full-stars">
<span class="review-full-timestamp">
<time itemprop="datePublished" datetime="2015-05-05T05:50:05-07:00">May 5, 2015</time>
</span>
</div>
<div class="review-full-review-comment-wrap"></div>
////*Append GREATER THAN*////
</div>

Related

get the month f the financial year in json

I have the selectbox with the option 2019-2020,2020-2021.I I choose the financial year 2019-2020 I want to display the month as {"month":["Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec","Jan","Feb","Mar"]}.
If I choose the financial year 2020-2021 I want to display the month {"month":["Apr","May"]}.
Is it possible to get the json based on selected financial year. can I get the json response in select option onclick
$('.financialyear').change(function(){
console.log($('.financialyear').val());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="financialyear" >
<option>2019-2020</option>
<option>2020-2021</option>
</select>
Try following code:
var months = [ "Jan","Feb","Mar", "Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec" ];
var starting_month = "Apr";
var current_year = new Date().getFullYear().toString();
var current_month = months[ new Date().getMonth() ];
$('.financialyear').change(function(){
console.clear();
var value = $('.financialyear').val();
var start_year = value.split('-')[0];
var index = months.indexOf( starting_month );
var count = 0;
var financial_months = [];
while( count < 12 ) {
financial_months.push( months[index] );
if ( current_year === start_year && current_month === months[index] ) {
break;
}
index++;
if ( index === months.length ) {
index = 0;
}
count++;
}
console.log( { months: financial_months } );
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="financialyear" >
<option value="2019-2020">2019-2020</option>
<option value="2020-2021">2020-2021</option>
</select>

Changing a ISO date to a Short date JavaScript

I currently have a function setup to get the following two weeks or months from the selected date from a input date field. However, the problem I'm facing is that I want to get the date to output DD/MM/YYYY but I'm getting the full ISO date where I need the short. Does anyone know how I can go about doing this?
EDIT:
I've added the moment(date1).format('DD/MM/YYYY'); to test the code but this hasn't provided any results.
function submit() {
var type = document.getElementById("selectType").value;
var dateSelected = document.getElementById('datePicker').valueAsDate = new Date();
if (type === "Months") {
document.getElementById("pWeeks").className = "hidden";
document.getElementById("pMonths").className = "";
var date1 = dateSelected;
moment(date1).format('DD/MM/YYYY');
var date2 = new Date(date1);
date2.setMonth(date2.getMonth() + 1);
document.getElementById("pM1").innerHTML = date1;
document.getElementById("pM2").innerHTML = date2;
} else {
document.getElementById("pWeeks").className = "";
document.getElementById("pMonths").className = "hidden";
var date1 = dateSelected;
var date2 = new Date(date1);
date2.setDate(date2.getDate() + 7);
document.getElementById("pW1").innerHTML = date1;
document.getElementById("pW2").innerHTML = date2;
}
}
.hidden {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<input type="date" id="datePicker"><br>
<select id="selectType">
<option value="Months">Months</option>
<option value="Weeks">Weeks</option>
</select><br>
<button id="submit" onclick="submit()">Submit</button>
<div id="pMonths" class="">
<p id="pM1"></p>
<p id="pM2"></p>
</div>
<div id="pWeeks" class="">
<p id="pW1"></p>
<p id="pW2"></p>
</div>
First off, you are setting the input value to the current date right here
var dateSelected = document.getElementById('datePicker').valueAsDate = new Date();
don't do that, it kind of defeats the purpose of having a selector in the first place.
As for converting the Dates, I would use Date.prototype.toLocaleDateString() passing "en-US" as the locale:
console.log((new Date()).toLocaleDateString('en-US')); // format MM/DD/YYY
I also fixed how you set the new dates, it now takes one date and adds either one and two months or one and to weeks instead of none and one month and none and one week ;-)
function submit() {
var type = document.getElementById("selectType").value;
var dateSelected = document.getElementById('datePicker').valueAsDate;
if (type === "Months") {
document.getElementById("pWeeks").className = "hidden";
document.getElementById("pMonths").className = "";
var date1 = dateSelected;
var datePlusOne = new Date(date1);
datePlusOne.setMonth(date1.getMonth() + 1);
var datePlusTwo = new Date(date1);
datePlusTwo.setMonth(date1.getMonth() + 2);
document.getElementById("pM1").innerHTML = datePlusOne.toLocaleDateString('en-US');
document.getElementById("pM2").innerHTML = datePlusTwo.toLocaleDateString('en-US');
} else {
document.getElementById("pWeeks").className = "";
document.getElementById("pMonths").className = "hidden";
var date1 = dateSelected;
var datePlusOne = new Date(date1);
datePlusOne.setDate(date1.getDate() + 7);
var datePlusTwo = new Date(date1);
datePlusTwo.setDate(date1.getDate() + 14);
document.getElementById("pW1").innerHTML = datePlusOne.toLocaleDateString('en-US');
document.getElementById("pW2").innerHTML = datePlusTwo.toLocaleDateString('en-US');
}
}
.hidden {
display: none;
}
<input type="date" id="datePicker"><br>
<select id="selectType">
<option value="Months">Months</option>
<option value="Weeks">Weeks</option>
</select><br>
<button id="submit" onclick="submit()">Submit</button>
<div id="pMonths" class="">
<p id="pM1"></p>
<p id="pM2"></p>
</div>
<div id="pWeeks" class="">
<p id="pW1"></p>
<p id="pW2"></p>
</div>
Instead of document.getElementById("pM1").innerHTML = date1; you should build first a string with the methods provided by the date object ( getFullYear, getDate, getMonth; see docu ). Then you can assign the string to the innerHtml.
If you can use the moment.js then your code which you assign to your innerHtml is date1 = moment(dateSelected).format('DD/MM/YYYY')
Also I would recommend Luca's way:
As for converting the Dates, I would use Date.prototype.toLocaleDateString() passing "en-US"
which would look at your code:
dateSelected.toLocaleDateString('en-US')
You could use MomentJS library to keep things simple:
Include the library :
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment.min.js"></script>
document.getElementById("pM1").innerHTML = moment(date1).format('DD/MM/YYYY');
document.getElementById("pM2").innerHTML = moment(date2).format('DD/MM/YYYY');
and in the else:
document.getElementById("pW1").innerHTML = moment(date1).format('DD/MM/YYYY');
document.getElementById("pW2").innerHTML = moment(date2).add(1, 'week').format('DD/MM/YYYY');

How to stop incorrect value in datepicker when previous data select in JavaScript?

Here, I got code for disable date in datepicker. when user select previous date then it alert to put a valid future date. It's working.
But It's printing whatever we select previous date. I want to stop print when previous date select. Thanks in advance.
<div class="col-md-8">
<input class="form-control datepicker" id="datepicker" onchange="checkDate()" required type="date" name="smexdate" value="<?=$promotion_details['expiry_date']?>" data-date-format="yyyy-mm-dd">
</div>
and JavaScript below.
function checkDate() {
var selectedText = document.getElementById('datepicker').value;
var selectedDate = new Date(selectedText);
var now = new Date();
if (selectedDate < now)
{
alert("Date must be in the future");
return false;
}
}
How about this?
var lastData;
function checkDate() {
var selectedText = document.getElementById('datepicker').value;
var selectedField = document.getElementById('datepicker');
var selectedDate = new Date(selectedText);
var now = new Date();
if (selectedDate < now)
{
console.log(lastData)
selectedField.value = (lastData) ? lastData : '';
alert("Date must be in the future");
return 0;
}
var theDate = new Date(selectedText);
var month = theDate.getMonth() + 1;
var date = theDate.getDate();
var year = theDate.getFullYear();
lastData = year + "-" + String("0" + month).slice(-2) + "-" + String("0" + date).slice(-2);
}

Compare date and string with jquery

I'm trying to compare today date and the date from the string. They both has a string type. Why do I get "no!" ?
jQuery(document).ready(function () {
Date.prototype.today = function () {
return ((this.getDate() < 10) ? "0" : "") + this.getDate() + "/" +(((this.getMonth() + 1) < 10) ? "0" : "") + (this.getMonth() + 1) + "/" + this.getFullYear();
}
datetodayvar = new Date().today();
deadlinadate = '16/10/2016';
if (String(datetodayvar) >= String(deadlinadate)) {
alert("yes!");
} else {
alert("no!");
}
});
Turn them both to Date objects instead of strings.
jQuery(document).ready(function () {
Date.prototype.today = function () {
return ((this.getDate() < 10)?"0":"") + this.getDate() +"/"+(((this.getMonth()+1) < 10)?"0":"") + (this.getMonth()+1) +"/"+ this.getFullYear();
}
datetodayvar = new Date().today();
deadlinadate = '02/11/2016';
if(new Date(datetodayvar) >= new Date(deadlinadate)) {
alert("yes!");
} else {
alert("no!");
} });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
If you have your "date string" from 3 different input fields(dropdowns or whatever) don't input a string, but make the date format as follows.
var year = 2015;
var month = 2-1; // February
var day = 27;
var now = new Date(year, month, day);
That way, you don't have to worry about date notation, localisation, if you need to use a - a . or / or something else inbetween.
Also remember the month, is always -1 because it starts counting as 0(januari being 0, december being 11.
Also, keep mind of day light savings time. That might go hayward with your freshly minted date objects too by subtracting an hour.
The snippet below has all the things i'd use in a "simple" comparing mechanism.
jQuery(document).ready(function () {
var str = '';
for(var c=1;c<32;c++) {
str += '<option value="'+c+'">'+c+'</option>';
}
$('#day').html(str);
var str = '';
for(var c=0;c<12;c++) {
str += '<option value="'+c+'">'+(c+1)+'</option>';
}
$('#month').html(str);
var str = '';
for(var c=parseInt(new Date().getFullYear());c>1990;c--) {
str += '<option value="'+c+'">'+c+'</option>';
}
$('#year').html(str);
$('#istodaycheck').on('click',function() {
var day = $('#day').get(0);
var month = $('#month').get(0);
var year = $('#year').get(0);
var date = new Date(
year.options[year.selectedIndex].value,
month.options[month.selectedIndex].value,
day.options[day.selectedIndex].value);
date.correctDst();
$('#output').text(date.isToday() ? 'yes' : 'no');
});
});
/**
* Retrieve standard timezome offset
*/
Date.prototype.stdTimezoneOffset = function() {
var jan = new Date(this.getFullYear(), 0, 1);
var jul = new Date(this.getFullYear(), 6, 1);
return Math.max(jan.getTimezoneOffset(), jul.getTimezoneOffset());
}
/**
* Checks if date is in day lights savings
*/
Date.prototype.dst = function() {
return this.getTimezoneOffset() < this.stdTimezoneOffset();
}
/**
* corrects the unwanted substraction of an hour on fresh dates.
*/
Date.prototype.correctDst = function() {
if(!this.dst()) {
this.setHours(this.getHours()+1);
}
}
/**
* Returns a date instance without time components.
*/
Date.prototype.justDate = function() {
var date = new Date(this.getFullYear(),this.getMonth(),this.getDate());
date.correctDst();
return date;
}
/**
* Tests if given date is today.
*/
Date.prototype.isToday = function() {
// strip possible time part.
var testdate = this.justDate();
var datetodayvar = new Date().justDate();
return datetodayvar.getTime() == testdate.getTime()
}
#output {
background-color: #eee;
border: 1px solid pink;
display: block;
width: 100%;
height:200px;
text-align: center;
font-size:121pt;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="day">
</select>
<select id="month">
</select>
<select id="year">
</select>
<button id="istodaycheck">Is this date today?</button>
<div id="output">
</div>
When comparing dates, always work with Date objects. The caveat with this is that when creating the objects, the provided date strings have to be in d/m/y or d-m-y format. Also note that today is not 16/10/2016.
jQuery(document).ready(function() {
var datetodayvar = new Date();
var deadlinadate = new Date('2/11/2016');
if (datetodayvar >= deadlinadate) {
console.log("yes!");
} else {
console.log("no!");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
First of all you are wrongly comparing two strings as if they were the numbers, when you do like this,
if(String(datetodayvar) >= String(deadlinadate)) { }
because if you want to compare strings you would have to
if(String(datetodayvar).equals(String(deadlinadate))){...
otherwise you compare the memory locations and not actual values.
Read more What is the difference between == vs equals() in Java?
This code will check whether the two string objects are greater than or equal to each other alphabetically, and not according to your actual requirement of date comparision. The functional code would be like this:
jQuery(document).ready(function () {
Date.prototype.today = function () {
return ((this.getDate() < 10)?"0":"") + this.getDate() +"/"+(((this.getMonth()+1) < 10)?"0":"") + (this.getMonth()+1) +"/"+ this.getFullYear();
}
datetodayvar = new Date().today();
deadlinadate = '02/11/2016';
if(new Date(datetodayvar) >= new Date(deadlinadate)) {
console.log("yes!");
} else {
console.log("no!");
} });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Assuming date format as dd/mm/yyyy and that deadline >= today
var ar = '02/11/2016'.split('/').map(Number);
var valid = new Date(ar[2],ar[1]-1,ar[0]) >= new Date().setHours(0,0,0,0);
console.log(valid);

How I can interpret the correct date in Javascript when the year is of the format yy?

I have defined an input that accepts only dates in HTML.
The user can enter the date manually or by using a Calendar which is defined in javascript.
I am using Javascript and Jquery to convert the input to a date:
var lStartDateText = $j("#DateStarte").val();
var lEndDateText = $j("#DateEnd").val();
var lEffStartDate = new Date(lStartDateText);
var lEffEndDate = new Date(lEndDateText);
My problem is that when the user enters the following date manually 1/1/50 is interpreted as 1/1/1950 but 1/1/49 is interpreted as 1/1/2049. I want it always to be interpreted as 20xx.
On the other hand the Calendar allows the user to choose a year from 2006 to 2021 in case the user wants to choose a date from it and not enter it manually.
Hope I can get some help here ??
Try this
var lStartDateText = $j("#DateStarte").val();
var lEndDateText = $j("#DateEnd").val();
var lEffStartDate = ReFormatDate(lStartDateText);
var lEffEndDate = ReFormatDate(lEndDateText);
function ReFormatDate(dateString) {
var dateParts = dateString.split("/");
if (dateParts[2].length === 2) {
dateParts[2] = "20" + dateParts[2];
}
return new Date(dateParts.join("/"));
}
use this
var lStartDateText = "1/1/50" ;
var lEndDateText = "1/1/49" ;
var res = lStartDateText.slice(4);
var starttext = lStartDateText.replace(res,"20"+res);
var res1 = lEndDateText.slice(4);
var endtext = lEndDateText.replace(res1,"20"+res1);
alert(starttext);
alert(endtext);
var lEffStartDate = new Date(starttext);
alert("start date"+lEffStartDate);
var lEffEndDate = new Date(endtext);
alert("End Date"+lEffEndDate);
If you know your getting the last 2 digits of the year (50), and you know you always want to add the first 2 digits, which are constant (20), that's a slight modification to your code:
var lStartDateText = '20' + $j("#DateStarte").val();
var lEndDateText = '20' + $j("#DateEnd").val();
Note that this is not particularly robust, e.g. if the user enters text which is not a date you might end up with a string like '20hi', but that may be outside the scope of your question and it will be parsed as an invalid date.
$('#year').on('change keyup', function() {
var y = $('#year').val();
if (y.length === 2) {
y = '20' + y
}
if (y.length === 4) {
var dateY = new Date();
dateY.setFullYear(y);
$('#result').html(dateY);
} else {
$('#result').html('No YY or YYYY date found');
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<label for="year">Enter year (YY or YYYY)</label>
<input id="year" type="text">
<div id="result"></div>
i hope it's will be help you.
$('#year').on('change keyup', function() {
var right_date = $('#year').val();
var data = $('#year').val().split('/');
if (data[2].length == 2){
var twoDigitsCurrentYear = parseInt(new Date().getFullYear().toString().substr(0,2));
$('#result').html(data[0]+'/'+data[1]+'/'+twoDigitsCurrentYear + data[2]);
}
else {
$('#result').html(right_date);
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<label for="year">Enter year (YY or YYYY)</label>
<input id="year" type="text" placeholder="dd/mm/yy">
<div id="result"></div>

Categories

Resources