Date value in JS results in 12/31/1969 4:00 PM - javascript

I have the following code snippet which is giving me fits. I just want to fetch the latest date, instead I get 12/31/1969 4:00 PM. Code is below, any/all help greatly appreciated.
if (setPass) {
var lastDate = new Date().toJSON();
for (var k = passVal.Values.length - 1; k >= 1; k--) {
if (passVal.Values[k].Average !== passVal2.Values[k].Average) {
lastDate = passVal.Values[k].Date.toUTCString();
break;
}
}
}
var passView = {
ID: id,
lastDate: lastDate
};
results.push(passView);
}

The format you need that is a String, So you you can build your own one. Like,
var date = new Date().getDate() < 10 ? '0' + new Date().getDate() : new Date().getDate();
var month = new Date().getMonth() < 10 ? '0' + new Date().getMonth() : new Date().getMonth();
var year = new Date().getFullYear();
var fullYear = month +'/'+ date +'/'+ year ;
console.log(fullYear);
then you can pass it. Cheers :).

Related

remove timezone in my random date generator in javascript

This is my code. I make it random but the timezone is always in there and i dont know how to disappear the timezone, can someone help me with this I'am beginner in this thanks
var startDate = new Date("1990-01-01"); //YYYY-MM-DD
var endDate = new Date("2022-01-01"); //YYYY-MM-DD
function formatDate(date) {
const year = date.getFullYear();
/* getMonth returns dates from 0, so add one */
const month = date.getMonth() + 1;
const day = date.getDate();
return `${year}-${month < 10 ? '0' : ''}${ month }-${ day < 10 ? '0' : '' }${day}`
}
var getDateArray = function(start, end) {
return new Date(
start.getTime() + Math.random() * (end.getTime(0) - start.getTime(0))
);
}
var dateArr = getDateArray(startDate, endDate);
console.log(dateArr);
If you call the formatDate function you have in your code, I believe that will get rid of the timezone information.
var startDate = new Date("1990-01-01"); //YYYY-MM-DD
var endDate = new Date("2022-01-01"); //YYYY-MM-DD
function formatDate(date) {
const year = date.getFullYear();
/* getMonth returns dates from 0, so add one */
const month = date.getMonth() + 1;
const day = date.getDate();
return `${year}-${month < 10 ? '0' : ''}${ month }-${ day < 10 ? '0' : '' }${day}`
}
var getDateArray = function(start, end) {
return formatDate(new Date(
start.getTime() + Math.random() * (end.getTime(0) - start.getTime(0))
));
}
var dateArr = getDateArray(startDate, endDate);
console.log(dateArr);
All I did here was add a call to your formatDate function within the getDateArray function so that now the return of the getDateArray will no longer contain timezone information.
Create these 2 functions to change the date format.
function DateFormat(startDate)
{
const strYear = date("Y",strtotime(strDate));
const strMonth= date("n",strtotime(strDate));
const strDay= date("j",strtotime(strDate));
return "${strYear}$-${strMonth}-${strDay}";
}
function DateFormat(endDate)
{
const strYear = date("Y",strtotime(strDate));
const strMonth= date("n",strtotime(strDate));
const strDay= date("j",strtotime(strDate));
return "${strYear}$-${strMonth}-${strDay}";
}

JavaScript: How to get simple date without timezone

I have code that generates random dates in a date range, which gives me dates which, when logged, produce this format:
Wed Sep 25 2019 05:00:00 GMT+0500 (Pakistan Standard Time)
I just want to get the date without timezone and Day specifically like this:
2019-09-25
I am trying to get random dates between specified dates using the following code:
var startDate = new Date("2019-08-26"); //YYYY-MM-DD
var endDate = new Date("2019-09-25"); //YYYY-MM-DD
var getDateArray = function(start, end) {
var arr = new Array();
var dt = new Date(start);
while (dt <= end) {
arr.push(new Date(dt));
dt.setDate(dt.getDate() + 1);
}
return arr;
}
var dateArr = getDateArray(startDate, endDate);
function shuffle(arra1) {
var ctr = arra1.length, temp, index;
// While there are elements in the array
while (ctr > 0) {
// Pick a random index
index = Math.floor(Math.random() * ctr);
// Decrease ctr by 1
ctr--;
// And swap the last element with it
temp = arra1[ctr];
arra1[ctr] = arra1[index];
arra1[index] = temp;
}
return arra1; }
console.log(shuffle(dateArr));
It's not a duplicate question as I was trying to achieve different and very specific formate.
One solution would be to map each item of arra1 through a custom formating function (ie formatDate()) where .getDate(), .getMonth() and .getYear() are used to populate the formatted string:
function formatDate(date) {
const year = date.getFullYear();
/* getMonth returns dates from 0, so add one */
const month = date.getMonth() + 1;
const day = date.getDate();
return `${year}-${month < 10 ? '0' : ''}${ month }-${ day < 10 ? '0' : '' }${day}`
}
Some points to consider here are:
Date#getMonth() returns 0-indexed dates in the range of 0-11. To match the desired date format, you should add 1 as shown
Check for day and month values that are less than 10 and prefix a 0 to pad those numbers to obtain the desired formatting
This can be added to your existing code as shown:
var startDate = new Date("2019-08-26"); //YYYY-MM-DD
var endDate = new Date("2019-09-25"); //YYYY-MM-DD
function formatDate(date) {
const year = date.getFullYear();
/* getMonth returns dates from 0, so add one */
const month = date.getMonth() + 1;
const day = date.getDate();
return `${year}-${month < 10 ? '0' : ''}${ month }-${ day < 10 ? '0' : '' }${day}`
}
var getDateArray = function(start, end) {
var arr = new Array();
var dt = new Date(start);
while (dt <= end) {
arr.push(new Date(dt));
dt.setDate(dt.getDate() + 1);
}
return arr;
}
var dateArr = getDateArray(startDate, endDate);
function shuffle(arra1) {
var ctr = arra1.length,
temp, index;
// While there are elements in the array
while (ctr > 0) {
// Pick a random index
index = Math.floor(Math.random() * ctr);
// Decrease ctr by 1
ctr--;
// And swap the last element with it
temp = arra1[ctr];
arra1[ctr] = arra1[index];
arra1[index] = temp;
}
/* Update this line */
return arra1.map(formatDate);
}
console.log(shuffle(dateArr));
Use .toISOString() and .substr(). Example:
var dt = new Date("2019-09-25");
console.log(dt.toISOString().substr(0,10)); // 2019-09-25
The advantage of this approach is that the Date object has the .toISOString() method built-in, so you don't have to reinvent the wheel. That method returns a full ISO string, though, like "2019-09-25T00:00:00.000Z". So, you can use .substr to retrieve only the part you want to use.
var getDates = function(startDate, endDate) {
var dates = [],
currentDate = startDate,
addDays = function(days) {
var date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
};
while (currentDate <= endDate) {
dates.push(currentDate);
currentDate = addDays.call(currentDate, 1);
}
return dates;
};
// Usage
var dates = getDates(new Date(2019, 10, 22),
new Date(2019, 11, 25));
dates.forEach(function(date) {
console.log(date);
});

Month/Day comparison in Javascript

I'm not an expert in JavaScript, but I've been tasked with migrating a very large website that was coded into PHP into a new CMS that does not allow server-side languages. I am therefore spending my days converting many PHP date-calcs to JavaScript.
Something very simple in PHP:
<?php
if (date('md') < 816) {$award_year = date('Y');}
if (date('md') > 815) {$award_year = date('Y') + 1;}
/*echo "year ".$award_year;*/
?>
This allows the year an application is due to automatically change to next year after August 15.
I've been trying to recreate this effect with Javascript and here is what I have come up with:
var today = new Date();
var mm = today.getMonth()+1; //January is 0!
var dd = today.getday();
if (mm < 10) {
mm = '0'+mm
}
currDate = mmdd;
var currDate = new Date();
var appDate = new Date("0816");
if (currDate < appDate){
var printDate = theDate.getFullYear();
}
else if (currDate >= appDate){
var printDate = theDate.getFullYear()+1;
}
I know that I am missing something, because the var currDate cannot just = mmdd and then be compared to another date. Can someone help me with the next step here ? I'm trying to actually learn JavaScript as I go rather than just blindly fix issues.
This will look similar to your PHP code:
const date = new Date();
const day = date.getUTCDate();
const month = date.getMonth();
const md = month + "" + day;
if (md < 816) {
var award_year = date.getFullYear();
}
else if (md > 815) {
var award_year = date.getFullYear() + 1;
}
console.log(award_year);
Instead of combining strings and comparing two dates you could check the current day and month to determine which year to return.
For example,
function getAwardYear() {
const today = new Date()
const AUGUST = 7
if (today.getMonth() >= AUGUST && today.getDate() > 15) {
return today.getFullYear() + 1
}
return today.getFullYear()
}
// Today: 6th Jun 2018
getAwardYear() // 2018
// Today: 16th Aug 2018
getAwardYear() // 2019
I know there is plenty of things to improvise the below code... I am leaving it for you to improvise...
var today = new Date();
var mm = today.getMonth()+1; //January is 0!
var dd = today.getDay();
if (mm < 10) {
mm = '0'+mm
}
var yyyy="2018"
var currDate = new Date(yyyy+"-"+mm+"-"+dd);
var appDate = new Date("2018-01-16");
alert("appDate"+appDate);
alert("currDate"+currDate);
if (currDate < appDate){
var printDate = currDate.getFullYear();
alert(printDate);
}
else if (currDate >= appDate){
var printDate = appDate.getFullYear()+1;
alert(printDate);
}

Javascript getDate() before this month

I have some pure javascript calendar.
my problem is that I want to add the days before the choosen month.
|so|mo|di|mi|do|fr|sa|
______________________
|29|30|31|1 |2 |3 | 4| <-- here 29,30,31
______________________
|5 |6 |.....
I hope it's clear what I mean. Here my script
<script type="text/javascript">
function Calendar(id, year, month) {
var elem = document.getElementById(id)
var mon = month - 1 // (1)
var d = new Date(year, mon)
var table = ['<table><tr>']
for (var i=0; i<d.getDay(); i++) {
table.push('<td></td>') // here days before this mounth
}
// main body (3)
while(d.getMonth() == mon) {
table.push('<td>'+d.getDate()+'</td>')
if (d.getDay() % 7 == 6) { // (4)
table.push('</tr><tr>')
}
d.setDate(d.getDate()+1)
}
n = 1
for (var i=d.getDay(); i<8; i++) {
table.push('<td>' + (n++) + '</td>')
}
table.push('</tr></table>')
elem.innerHTML = table.join('\n')
}
new Calendar("cal", 2015, 9)
</script>
I try around with setDate() but I don't mastered it jet.
As mentioned in the comments setDate (and the Date constructor) can have negative values. But instead of a pre and post loop, you could set the startdate to the beginning of the week and always add entire weeks:
function Calendar(id, year, month) {
var elem = document.getElementById(id)
var mon = month - 1; // (1)
var d = new Date(year, mon, 1 );
var start = 1-d.getDay();
var table = ['<table>'];
while(d.getMonth() <= mon) {
table.push('<tr>');
for(var i =0 ; i< 7; i++){
d = new Date(year,mon,start++);
table.push('<td>'+d.getDate() + '</td>')
}
table.push('</tr>');
}
table.push('</table>')
elem.innerHTML = table.join('\n')
}
new Calendar("cal", 2015, 9);
fiddle
edit: an alternate version just in case the 'other' months should have a lighter colour: fiddle
Try defining start and end dates for your month view and iterate from start to end.
var startDate = new Date(d);
var endDate = new Date(d.getFullYear(), d.getMonth() + 1, d.getDate() - 1);
while (startDate.getDay() != 0) {
startDate.setDate(startDate.getDate() - 1);
}
while (endDate.getDay() != 6) {
endDate.setDate(endDate.getDate() + 1);
}
I have managed it in this way:
tmp = new Date(year, mon, 0).getDate() // return day of the last month
for (var i=0; i<(d.getDay() + 6) % 7; i++) { // count days
table.splice(1,0,'<td>'+(tmp-i)+'</td>') // adding days at first pos of table
}
Thanks
Date object has method .setDate() for adding days to get updated date.
var someDate = new Date(2015, 06, 05); // (year, month, date)
console.log('old date : ' + someDate);
var numberOfDays = 6; // No of day add or remove. use negative sign for remove days
someDate.setDate(someDate.getDate() + numberOfDays); //date object with new date (new day, new month and new year)
console.log('new date : ' + someDate);

Validate date for anyone over 18 with jQuery

I have a form on my site that should validate for anyone who is over 18.
var day = $("#dobDay").val();
var month = $("#dobMonth").val();
var year = $("#dobYear").val();
var age = 18;
var mydate = new Date();
mydate.setFullYear(year, month-1, day);
var currdate = new Date();
currdate.setFullYear(currdate.getFullYear() - age);
var output = currdate - mydate
if ((currdate - mydate) > 0){
// you are not 18
}
But it working totally opposite way. I would like the if statement to take action when user is over under 18 years old.
Thank you for your help in advance
check this DEMO
var day = 12;
var month = 12;
var year = 2006;
var age = 18;
var setDate = new Date(year + age, month - 1, day);
var currdate = new Date();
if (currdate >= setDate) {
// you are above 18
alert("above 18");
} else {
alert("below 18");
}
var day = $("#dobDay").val();
var month = $("#dobMonth").val();
var year = $("#dobYear").val();
var age = 18;
var mydate = new Date();
mydate.setFullYear(year, month-1, day);
var currdate = new Date();
currdate.setFullYear(currdate.getFullYear() - age);
if(currdate < mydate)
{
alert('You must be at least 18 years of age.');
}
Here is a somewhat lighter version that I tested:
var day = 1;
var month = 1;
var year = 1999;
var age = 18;
var cutOffDate = new Date(year + age, month, day);
if (cutOffDate > Date.now()) {
$('output').val("Get Outta Here!");
} else {
$('output').val("Works for me!");
}
The key is to add the minimum age to the birthdate and confirm that it is before the current date. You are checking if the current date minus the minimum age (basically the latest birthdate allowed) was greater than than the birthdate provided, which will give you the reverse.
18 year old validation rule for jQuery Validator plugin using addMethod function.
jQuery.validator.addMethod(
"validDOB",
function(value, element) {
var from = value.split(" "); // DD MM YYYY
// var from = value.split("/"); // DD/MM/YYYY
var day = from[0];
var month = from[1];
var year = from[2];
var age = 18;
var mydate = new Date();
mydate.setFullYear(year, month-1, day);
var currdate = new Date();
var setDate = new Date();
setDate.setFullYear(mydate.getFullYear() + age, month-1, day);
if ((currdate - setDate) > 0){
return true;
}else{
return false;
}
},
"Sorry, you must be 18 years of age to apply"
);
and
$('#myForm')
.validate({
rules : {
myDOB : {
validDOB : true
}
}
});
if it's working the opposite way have you tried swapping the > for a < on the second to last line?
I think it will be easier to understand if we rename the variables
mydate => givenDate
currdate => thresholdDate
if givenDate > thresholdDate => you are not 18
else => you are 18
i.e.
if ( givenDate > thresholdDate ){
// you are not 18
}
i.e
if ((givenDate - thresholdDate) > 0){
// you are not 18
}
i.e.
if ((mydate - currdate ) > 0){
// you are not 18
}

Categories