How do I create a random UNIX timestamp using JavaScript:
Between now and the end of the working day (i.e. today between 08:00-17:00) if appointment.status === "today".
From tomorrow + 1 week but keeping in mind the working day (so it can be next week Tuesday 13:00, keeping in mind the working day i.e. 08:00-17:00) if appointment.status === "pending".
This is what I have done so far:
if(appointment.status === "today") {
appointment.timestamp = (function() {
return a
})();
} else if(appointment.status === "pending") {
appointment.timestamp = (function() {
return a
})();
}
This is similar to another question (Generate random date between two dates and times in Javascript) but to handle the "pending" appointments you'll also need a way to get a day between tomorrow and a week from tomorrow.
This function will return a random timestamp between 8:00 and 17:00 on the date that is passed to it:
var randomTimeInWorkday = function(date) {
var begin = date;
var end = new Date(begin.getTime());
begin.setHours(8,0,0,0);
end.setHours(17,0,0,0);
return Math.random() * (end.getTime() - begin.getTime()) + begin.getTime();
}
To get a random timestamp today between 08:00 and 17:00 today you could do:
var today = new Date();
var timestamp = randomTimeInWorkday(today);
console.log(timestamp); // 1457033914204.1597
console.log(new Date(timestamp)); // Thu Mar 03 2016 14:38:34 GMT-0500 (EST)
This function will return a random date between tomorrow and a week from tomorrow for the date that is passed to it:
var randomDayStartingTomorrow = function(date) {
var begin = new Date(date.getTime() + 24 * 60 * 60 * 1000);
var end = new Date(begin.getTime());
end.setDate(end.getDate() + 7);
return new Date(Math.random() * (end.getTime() - begin.getTime()) + begin.getTime());
}
To get a random timestamp between 08:00 and 17:00 on a random day between tomorrow and a week from tomorrow, you could do:
var today = new Date();
var randomDay = randomDayStartingTomorrow(today);
var timestamp = randomTimeInWorkday(randomDay);
console.log(timestamp); // 1457194668335.3162
console.log(new Date(timestamp)); // Sat Mar 05 2016 11:17:48 GMT-0500 (EST)
Related
I have converted the timestamp 4/1/2021 00:00 into the format Thu Apr 01 2021 00:00:00 GMT-0500 (Central Daylight Time) as shown in the code below. However, adding 30 days is not giving me appropriate result.
//Handling Date String: 4/1/2021 00:00
function setStart(input) {
if (!(input instanceof Date))
console.log('Handling Date String:' +input)
input = new Date(Date.parse(input));
input.setHours(0);
input.setMinutes(0);
input.setSeconds(0);
input.setMilliseconds(0);
start = input;
return start;
}
var initialDate = setStart('4/1/2021 00:00');
console.log("Printing converted date below:");
console.log(setStart('4/1/2021 00:00'));
var date = new Date(); // Now
//date.setDate(date.getDate() + 30); // Set now + 30 days as the new date
date.setDate(initialDate + 30);
console.log("Printing date after adding 30 days below")
console.log(date);
/* var getDaysArray = function(start, end) {
for(var arr=[],dt=new Date(start); dt<=new Date(end); dt.setDate(dt.getDate()+1)){
arr.push(new Date(dt));
}
return arr;
};
var daylist = getDaysArray(new Date("2018-05-01"),new Date("2018-06-01"));
console.log(daylist); */
The browser's console is printing it like the following:
Handling Date String:4/1/2021 00:00
Printing converted date below:
Handling Date String:4/1/2021 00:00
Thu Apr 01 2021 00:00:00 GMT-0500 (Central Daylight Time)
Printing date after adding 30 days below
Invalid Date
What is causing it to print Invalid Date ?
You want to get the date after 30 days from the initialDate, don't you?
refer this
var date = new Date(initialDate); // Now
//date.setDate(date.getDate() + 30); // Set now + 30 days as the new date
date.setDate(date.getDate() + 30);
console.log("Printing date after adding 30 days below")
console.log(date);
You should something like
var date = new Date().getTime(); // Now
const offset = 30*23*3600*1000;
const newDate = new Date(date+offset).toLocaleString('en-US', {timeZone: 'CST'}); // Change added
console.log("Printing date after adding 30 days below")
console.log(newDate);
I want to compare 2 dates and time, for this, I am getting data in timestamp and I convert timestamp in date but now how can I compare it?
exp time: 1580109819
expD: Mon Jan 27 2020 12:53:39 GMT+0530 (India Standard Time)
newDateTime: Mon Jan 27 2020 11:54:21 GMT+0530 (India Standard Time)
this.logData.exp = 1580109819;
console.log("exp time: ", this.logData.exp);
var expD = new Date(this.logData.exp * 1000);
console.log("expD: ", expD);
console.log(expD.getDate() + '-' + (expD.getMonth() + 1) + '-' + expD.getFullYear() + ' ' + expD.getTime());
var currentD = new Date(this.logData.exp * 1000);
let dateString = currentD.toUTCString();
console.log(dateString);
let newDateTime = new Date()
console.log("newDateTime: ", newDateTime);
You can save those date strings as Date objects.
So below code in the comparison to Two dates with Javascript.
var currentDate = new Date("2020-01-27");
var pastDate = new Date("2020-01-20");
if (pastDate < currentDate) {
currentDate = currentDate.setDate(currentDate.getDate() + 30);
}
$scope.pastDate = pastDate;
$scope.currentDate = currentDate;
using momentJs, for example:
var date = moment("2013-03-24")
var now = moment();
if (now > date) {
// date is past
} else {
// date is future
}
You can compare it as timestamps, without converting into Date object.
Assuming this.logData is already in timestamp (seconds), converting it into milli seconds for comparison.
New date is created using date object constructor and then converted into timestamp using method, getTime().
// For converting into milli seconds.
const expDateTimestamp = this.logData.exp * 1000;
// New date timestamp
const newDateTime = new Date();
const newDateTimeStamp = newDateTime.getTime();
// Comparison
if (expDateTimestamp < newDateTimeStamp) {
} else {
}
Use Date.prototype.getTime()
currentD.getTime() > newDateTime.getTime()
I have problem while substracting time from current date. My Code looks like:
var d = new Date(),
year = d.getUTCFullYear(),
month = ('0'+(d.getUTCMonth()+1)).slice(-2),
day = ('0'+d.getUTCDate()).slice(-2),
hour = ('0'+d.getUTCHours()).slice(-2),
minute = ('0'+d.getUTCMinutes()).slice(-2),
second = ('0'+d.getUTCSeconds()).slice(-2);
var startDate = year+'/'+month+'/'+day+'-'+hour+':'+minute+':'+second;
console.log(startDate);
You can simply use like below
var fiveMinuteAgo = new Date( Date.now() - 1000 * (60 * 5) )
Get the milliseconds of the date variable, substract 5 minutes and create a new date object from it:
var d = new Date()
// d = Mon Feb 29 2016 08:00:09 GMT+0100 (W. Europe Standard Time)
var milliseconds = Date.parse(d)
// 1456729209000
milliseconds = milliseconds - (5 * 60 * 1000)
// - 5 minutes
d = new Date(milliseconds)
// d = Mon Feb 29 2016 07:55:04 GMT+0100 (W. Europe Standard Time)
If you are ready to use new date manipulation js called as moment js.
You can simply do it in one function as below:
moment().subtract(5, 'minutes');
Moment JS Docs
You could use like this
var original = new Date();
var subtract5min = new Date();
alert("before : " + original);
subtract5min.setTime(original.getTime() - 5*60*1000);
alert("after : " + subtract5min);
You can simply substract by
minute = ('0'+d.getUTCMinutes()).slice(-2)-5
var d = new Date(),
year = d.getUTCFullYear(),
month = ('0'+(d.getUTCMonth()+1)).slice(-2),
day = ('0'+d.getUTCDate()).slice(-2),
hour = ('0'+d.getUTCHours()).slice(-2),
minute = ('0'+d.getUTCMinutes()).slice(-2),
second = ('0'+d.getUTCSeconds()).slice(-2);
if (minute>=5)
minute = minute-5;
else {
minute = (parseInt(minute) + 60) - 5;
hour = hour - 1;
}
var startDate = year+'/'+month+'/'+day+'-'+hour+':'+minute+':'+second;
alert(startDate);
I have created the following code (which works) to print something different based on the weeks of a specified month:
<script language="javascript">
<!--
var advent;
mytime=new Date();
mymonth=mytime.getMonth()+1;
mydate=mytime.getDate();
if (mymonth==12 && (mydate >= 1 && mydate <= 6)){document.write("xxx");
}
if (mymonth==12 && (mydate >= 7 && mydate <= 13)){document.write("yyy");
}
if (mymonth==12 && (mydate >= 14 && mydate <= 20)){document.write("zzz");
}
if (mymonth==12 && (mydate >= 21 && mydate <= 30)){document.write("qqq");
}
//-->
</script>
But I need this to change for Advent each year and Advent changes based on when Christmas falls each year:
Advent starts on the Sunday four weeks before Christmas Day. There are
four Sundays in Advent, then Christmas Day. The date changes from year
to year, depending on which day of the week Christmas fall. Thus, in
2010, Advent began on 28 November. In 2011, it will occur on 27
November.
How do I calculate when the weeks of Advent begin each year?
Start with a Date that's exactly 3 weeks before Christmas Eve. Then, walk backwards until the day-of-week is Sunday:
function getAdvent(year) {
//in javascript months are zero-indexed. january is 0, december is 11
var d = new Date(new Date(year, 11, 24, 0, 0, 0, 0).getTime() - 3 * 7 * 24 * 60 * 60 * 1000);
while (d.getDay() != 0) {
d = new Date(d.getTime() - 24 * 60 * 60 * 1000);
}
return d;
}
getAdvent(2013);
// Sun Dec 01 2013 00:00:00 GMT-0600 (CST)
getAdvent(2012);
// Sun Dec 02 2012 00:00:00 GMT-0600 (CST)
getAdvent(2011);
// Sun Nov 27 2011 00:00:00 GMT-0600 (CST)
(2013 and 2012 were tested and verified against the calendar on http://usccb.org/. 2011 was verified against http://christianity.about.com/od/christmas/qt/adventdates2011.htm)
Here's what I was talking about in my comment:
function getAdvent(year) {
var date = new Date(year, 11, 25);
var sundays = 0;
while (sundays < 4) {
date.setDate(date.getDate() - 1);
if (date.getDay() === 0) {
sundays++;
}
}
return date;
}
DEMO: http://jsfiddle.net/eyUjX/1/
It starts on Christmas day, in the specific year. It goes into the past, day by day, checking for Sunday (where .getDate() returns 0). After 4 of them are encountered, the looping stops and that Date is returned.
So to get 2009's beginning of Advent, use: getAdvent(2009);. It returns a Date object, so you can still work with its methods.
As a reference of its methods: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date
You can get Advent Sunday by adding 3 days to the last Thursday in November, which seems simpler:
function getAdventDay(y){
var advent=new Date();
advent.setHours(0,0,0,0);
//set the year:
if(typeof y!='number')y=advent.getFullYear();
//get the last day of november:
advent.setFullYear(y,10,30);
//back up to the last thursday in November:
while(advent.getDay()!==4)advent.setDate(advent.getDate()-1);
//add 3 days to get Sunday:
advent.setDate(advent.getDate()+3);
return advent;
}
getAdventDay(2013)
/*
Sun Dec 01 2013 00:00:00 GMT-0500 (Eastern Standard Time)
*/
const getFirstAdvent=function(y){
const firstAdvent=new Date(y,11,3);
firstAdvent.setDate(firstAdvent.getDate()-firstAdvent.getDay());
return firstAdvent;
};
alert(getFirstAdvent(2020));
I love these challenges, here's how it can be done with recursion. First I find the fourth Sunday. Then I Just keep minusing 7 days until I have the other 3. The variables firstSunday, secondSunday, thirdSunday and fourthSunday - contains the dates.
EDIT: I believe I misunderstood, but the firstSunday variable Will be the date you are looking for.
Demo
Javascript
var year = 2011;//new Date().getFullYear();
var sevenDays = (24*60*60*1000) * 7;
var foundDate;
var findClosestSunday = function(date){
foundDate = date;
if (foundDate.getDay() != 0)
findClosestSunday(new Date(year,11,date.getDate()-1));
return foundDate;
}
var fourthSunday = findClosestSunday(new Date(year, 11, 23));
var thirdSunday = new Date(fourthSunday.getTime() - sevenDays);
var secondSunday = new Date(fourthSunday.getTime() - sevenDays *2);
var firstSunday = new Date(fourthSunday.getTime() - sevenDays *3);
console.log
(
firstSunday,
secondSunday,
thirdSunday,
fourthSunday
);
Javascript works with time in terms of milliseconds since epoch. There are 1000 * 60 * 60 *24 * 7 = 604800000 milliseconds in a week.
You can create a new date in Javascript that is offset from a know date doing this:
var weekTicks, christmas, week0, week1, week2, week3;
weekTicks = 604800000;
christmas = new Date(2013, 12, 25);
week0 = new Date(christmas - weekTicks);
week1 = new Date(week0 - weekTicks);
week2 = new Date(week1 - weekTicks);
week3 = new Date(week2 - weekTicks);
See how that works for you.
Also, the Date.getDay function will work to help you find which day of the month is the first Sunday.
I have a current Date object that needs to be incremented by one day using the JavaScript Date object. I have the following code in place:
var ds = stringFormat("{day} {date} {month} {year}", {
day: companyname.i18n.translate("day", language)[date.getUTCDay()],
date: date.getUTCDate(),
month: companyname.i18n.translate("month", language)[date.getUTCMonth()],
year: date.getUTCFullYear()
});
How can I add one day to it?
I've added +1 to getUTCDay() and getUTCDate() but it doesn't display 'Sunday'
for day, which I am expecting to happen.
To add one day to a date object:
var date = new Date();
// add a day
date.setDate(date.getDate() + 1);
In my humble opinion the best way is to just add a full day in milliseconds, depending on how you factor your code it can mess up if you are on the last day of the month.
For example Feb 28 or march 31.
Here is an example of how I would do it:
var current = new Date(); //'Mar 11 2015' current.getTime() = 1426060964567
var followingDay = new Date(current.getTime() + 86400000); // + 1 day in ms
followingDay.toLocaleDateString();
Imho this insures accuracy
Here is another example. I do not like that. It can work for you but not as clean as example above.
var today = new Date('12/31/2015');
var tomorrow = new Date(today);
tomorrow.setDate(today.getDate()+1);
tomorrow.toLocaleDateString();
Imho this === 'POOP'
So some of you have had gripes about my millisecond approach because of day light savings time. So I'm going to bash this out. First, Some countries and states do not have Day light savings time. Second Adding exactly 24 hours is a full day. If the date number does not change once a year but then gets fixed 6 months later I don't see a problem there. But for the purpose of being definite and having to deal with allot the evil Date() I have thought this through and now thoroughly hate Date. So this is my new Approach.
var dd = new Date(); // or any date and time you care about
var dateArray = dd.toISOString().split('T')[0].split('-').concat( dd.toISOString().split('T')[1].split(':') );
// ["2016", "07", "04", "00", "17", "58.849Z"] at Z
Now for the fun part!
var date = {
day: dateArray[2],
month: dateArray[1],
year: dateArray[0],
hour: dateArray[3],
minutes: dateArray[4],
seconds:dateArray[5].split('.')[0],
milliseconds: dateArray[5].split('.')[1].replace('Z','')
}
Now we have our Official Valid international Date Object clearly written out at Zulu meridian.
Now to change the date
dd.setDate(dd.getDate()+1); // this gives you one full calendar date forward
tomorrow.setDate(dd.getTime() + 86400000);// this gives your 24 hours into the future. do what you want with it.
If you want add a day (24 hours) to current datetime you can add milliseconds like this:
new Date(Date.now() + ( 3600 * 1000 * 24))
int days = 1;
var newDate = new Date(Date.now() + days*24*60*60*1000);
CodePen
var days = 2;
var newDate = new Date(Date.now()+days*24*60*60*1000);
document.write('Today: <em>');
document.write(new Date());
document.write('</em><br/> New: <strong>');
document.write(newDate);
Inspired by jpmottin in this question, here's the one line code:
var dateStr = '2019-01-01';
var days = 1;
var result = new Date(new Date(dateStr).setDate(new Date(dateStr).getDate() + days));
document.write('Date: ', result); // Wed Jan 02 2019 09:00:00 GMT+0900 (Japan Standard Time)
document.write('<br />');
document.write('Trimmed Date: ', result.toISOString().substr(0, 10)); // 2019-01-02
Hope this helps
simply you can do this
var date = new Date();
date.setDate(date.getDate() + 1);
console.log(date);
now the date will be the date of tomorrow. here you can add or deduct the number of days as you wish.
This is function you can use to add a given day to a current date in javascript.
function addDayToCurrentDate(days){
let currentDate = new Date()
return new Date(currentDate.setDate(currentDate.getDate() + days))
}
// current date = Sun Oct 02 2021 13:07:46 GMT+0200 (South Africa Standard Time)
// days = 2
console.log(addDayToCurrentDate(2))
// Mon Oct 04 2021 13:08:18 GMT+0200 (South Africa Standard Time)
// Function gets date and count days to add to passed date
function addDays(dateTime, count_days = 0){
return new Date(new Date(dateTime).setDate(dateTime.getDate() + count_days));
}
// Create some date
const today = new Date("2022-02-19T00:00:00Z");
// Add some days to date
const tomorrow = addDays(today, 1);
// Result
console.log("Tomorrow => ", new Date(tomorrow).toISOString());
// 2022-02-20T00:00:00.000Z
We can get date of the day after today by using timedelta with numOfDays specified as 1 below.
from datetime import date, timedelta
tomorrow = date.today() + timedelta(days=1)
currentDay = '2019-12-06';
currentDay = new Date(currentDay).add(Date.DAY, +1).format('Y-m-d');