Increment date by one day to a set epoch date - javascript

I would like to increment a (epoch) date by one day.
So far I have:
let date = "1535162451650"; // August 24 2018
console.log(new Date(parseInt(date, 10)).getDate() + 1);
This spits out 25 so I am on the right track. How would I convert it back to a Date object?
This is going to be in this map function:
return data.map(t => ({
id: t.id,
start_date: new Date(parseInt(t.date_created, 10)),
duration: // here, taking the above start date and adding one day
)
}));

I think you can add day in milliseconds to achieve this.
let date = "1535162451650"; // August 24 2018
console.log(new Date(parseInt(date, 10)).getDate() + 1);
let nextDay = +date + (24 * 60 * 60 * 1000) // 1 day in millisecond
nextDay = new Date(nextDay)
console.log(nextDay)
You can also use momentjs in following way:
var date = 1535162451650
date = moment(abc)
console.log('date', date.format('DD MM YYYY'))
date = date.add(1, 'day')
console.log('date', date.format('DD MM YYYY'))

How about this?
var options = {
id: t.id,
start_date: new Date(parseInt(t.date_created, 10))
};
options.duration = new Date(options.start_date.getTime());
options.duration.setDate(options.duration.getDate() + 1);
return data.map(t => (options));

I think I figured it out. Looks ugly but seems to work
let date = "1535162451650";
console.log(new Date (new Date(parseInt(date, 10)).setDate(new Date(parseInt(date, 10)).getDate() + 1)));
// gives me aug 25 2018
Is there a cleaner way to do this? haha

Related

How to get unix timestamp from tomorrow nodejs

I want to get Unix timestamp (time in seconds) from tomorrow.
I have tried the following with no success:
var d = new Date();
d.setDate(d.getDay() - 1);
d.setHours(0, 0, 0);
d.setMilliseconds(0);
console.log(d/1000|0)
How would I fix the above?
Just modified your code and it works fine
var d = new Date();
d.setDate(d.getDate() + 1);
d.setHours(0, 0, 0);
d.setMilliseconds(0);
console.log(d)
>> Sun Apr 21 2019 00:00:00 GMT+0530 (India Standard Time)
Hope this will work for you
This should do it.
Copied directly from https://javascript.info/task/get-seconds-to-tomorrow
function getSecondsToTomorrow() {
let now = new Date();
// tomorrow date
let tomorrow = new Date(now.getFullYear(), now.getMonth(), now.getDate()+1);
let diff = tomorrow - now; // difference in ms
return Math.round(diff / 1000); // convert to seconds
}
console.log(getSecondsToTomorrow());
you could use a third party library like moment js which makes your life alot easier
momentjs
You can use a unix timestamp and add 24*60*60*1000 (same as 86400000) to the current time's timestamp. You can then pass that to new Date() like this:
24 = hours
60 = minutes
60 = seconds
1000 = converts the result to milliseconds
// Current timestamp
const now = Date.now()
// Get 24 hours from now
const next = new Date(now + (24*60*60*1000))
// Create tomorrow's date
const t = new Date(next.getFullYear(), next.getMonth(), next.getDate())
// Subtract the two and divide by 1000
console.log(Math.round((t.getTime() - now) / 1000), 'seconds until tomorrow')

How do I convert UTC/ GMT datetime to CST in Javascript? (not local, CST always)

I have a challenge where backend data is always stored in UTC time. Our front-end data is always presented in CST. I don't have access to this 'black box.'
I would like to mirror this in our data warehouse. Which is based in Europe (CET). So "local" conversion will not work.
I'm wondering the simplest, most straightforward way to accurately convert UTC time (I can have it in epoch milliseconds or a date format '2015-01-01 00:00:00') to Central Standard Time. (which is 5 or 6 hours behind based on Daylight Savings).
I see a lot of threads about converting to 'local' time ... again I don't want this, nor do I simply want to subtract 6 hours which will be wrong half the year.
Anyone have any ideas? This seems to be a very common problem but I've been searching for a while, and have found nothing.
Using moment.js with the moment-timezone add-on makes this task simple.
// construct a moment object with UTC-based input
var m = moment.utc('2015-01-01 00:00:00');
// convert using the TZDB identifier for US Central time
m.tz('America/Chicago');
// format output however you desire
var s = m.format("YYYY-MM-DD HH:mm:ss");
Additionally, since you are referring to the entire North American Central time zone, you should say either "Central Time", or "CT". The abbreviation "CST" as applied to North America explicitly means UTC-6, while the "CDT" abbreviation would be used for UTC-5 during daylight saving time.
Do be careful with abbreviations though. "CST" might mean "China Standard Time". (It actually has five different interpretations).
You can use the time zone offset to determine whether 5 or 6 hours should be subtracted.
var dateJan;
var dateJul;
var timezoneOffset;
var divUTC;
var divCST;
// Set initial date value
dateValue = new Date('10/31/2015 7:29:54 PM');
divUTC = document.getElementById('UTC_Time');
divCST = document.getElementById('CST_Time');
divUTC.innerHTML = 'from UTC = ' + dateValue.toString();
// Get dates for January and July
dateJan = new Date(dateValue.getFullYear(), 0, 1);
dateJul = new Date(dateValue.getFullYear(), 6, 1);
// Get timezone offset
timezoneOffset = Math.max(dateJan.getTimezoneOffset(), dateJul.getTimezoneOffset());
// Check if daylight savings
if (dateValue.getTimezoneOffset() < timezoneOffset) {
// Adjust date by 5 hours
dateValue = new Date(dateValue.getTime() - ((1 * 60 * 60 * 1000) * 5));
}
else {
// Adjust date by 6 hours
dateValue = new Date(dateValue.getTime() - ((1 * 60 * 60 * 1000) * 6));
}
divCST.innerHTML = 'to CST = ' + dateValue.toString();
<div id="UTC_Time"></div>
<br/>
<div id="CST_Time"></div>
Maybe you can use something like the following. Note, that is just an example you might need to adjust it to your needs.
let cstTime = new Date(createdAt).toLocaleString("es-MX", {
timeZone: "America/Mexico_City" });
You can use below code snippet for converting.
function convertUTCtoCDT() {
var timelagging = 6; // 5 or 6
var utc = new Date();
var cdt = new Date(utc.getTime()-((1 * 60 * 60 * 1000) * timelagging));
console.log("CDT: "+cdt);
}
let newDate = moment(new Date()).utc().format("YYYY-MM-DD HH:mm:ss").toString()
var m = moment.utc(newDate);
m.tz('America/Chicago');
var cstDate = m.format("YYYY-MM-DD HH:mm:ss");
You can use below code snippet
// Get time zone offset for CDT or CST
const getCdtCstOffset = () => {
const getNthSunday = (date, nth) => {
date.setDate((7*(nth-1))+(8-date.getDay()));
return date;
}
const isCdtTimezoneOffset = (today) => {
console.log('Today : ', today);
let dt = new Date();
var mar = new Date(dt.getFullYear(), 2, 1);
mar = getNthSunday(mar, 2);
console.log('CDT Start : ', mar);
var nov = new Date(dt.getFullYear(), 10, 1, 23, 59, 59);
nov = getNthSunday(nov, 1);
console.log('CDT End : ', nov);
return mar.getTime()< today.getTime() && nov.getTime()> today.getTime();
}
var today = new Date()// current date
if (isCdtTimezoneOffset(today)) {
return -5
} else {
return -6
}
}
let cstOrCdt = new Date();
cstOrCdt.setHours(cstOrCdt.getHours()+getCdtCstOffset())
console.log('CstOrCdt : ', cstOrCdt);

How to convert result from Date.now() to yyyy/MM/dd hh:mm:ss ffff?

I'm looking for something like yyyy/MM/dd hh:mm:ss ffff
Date.now() returns the total of milliseconds (ex: 1431308705117).
How can I do this?
You can use the Date constructor which takes in a number of milliseconds and converts it to a JavaScript date:
var d = new Date(Date.now());
d.toString() // returns "Sun May 10 2015 19:50:08 GMT-0600 (MDT)"
In reality, however, doing Date(Date.now()) does the same thing as Date(), so you really only have to do this:
var d = new Date();
d.toString() // returns "Sun May 10 2015 19:50:08 GMT-0600 (MDT)"
You can use native JavaScript Date methods to achieve that or you can use a library like Moment.js.
It is a simple as:
moment().format('YYYY/MM/D hh:mm:ss SSS')
If you are going use a lot of date formatting/parsing in your application then I definitely recommend using it.
You can use Date().toISOString(), i.e.:
let d = new Date().toISOString();
document.write(d);
Output:
2022-02-04T17:46:16.100Z
Demo:
let d = new Date().toISOString();
document.write(d);
Simple
const DateNow = Date.now(); // 1602710690936
console.log(new Date(DateNow).toString()) // returns "Sun May 10 2015 19:50:08 GMT-0600 (MDT)"
function formatted_date()
{
var result="";
var d = new Date();
result += d.getFullYear()+"/"+(d.getMonth()+1)+"/"+d.getDate() +
" "+ d.getHours()+":"+d.getMinutes()+":"+
d.getSeconds()+" "+d.getMilliseconds();
return result;
}
console.log(formatted_date())
Output: "2015/5/10 22:5:26 429"
function millisecondsToHuman(ms) {
const seconds = Math.floor((ms / 1000) % 60);
const minutes = Math.floor((ms / 1000 / 60) % 60);
const hours = Math.floor(ms / 1000 / 60 / 60);
const humanized = [
pad(hours.toString(), 2),
pad(minutes.toString(), 2),
pad(seconds.toString(), 2),
].join(':');
return humanized;
}
function pad(numberString, size) {
let padded = numberString;
while (padded.length < size) padded = `0${padded}`;
return padded;
}
Step 1: use new Date() to get the date as JavaScript format as Sun Jul 12 2020 15:40:16 GMT+0800 (Singapore Standard Time)
var d = new Date()
Step 2: use .toString() to convert to string and .substr string method to convert the previous string to "Jul 12 2020" and get rid of the rest
var d2 = d.toString().substr(4, 11)
Step 3: use .slice method to add '/' between dat, month and year to get Jul / 12 / 2020
var d3 = d2.slice(0, 3) + ' /' + d2.slice(3, 6) + ' /' + d2.slice(6))
const formattedDate = () => {
d = new Date()
cd = num => num.toString().padStart(2, 0)
return d.getFullYear()+"/"+cd(d.getMonth() + 1)+"/"+cd(d.getDate()) +
" "+ cd(d.getHours())+":"+cd(d.getMinutes())+":"+
cd(d.getSeconds())+" "+d.getMilliseconds()
}
console.log(formattedDate) //returns "2022/11/01 03:00:36 777"
var date = new Date();
will get you an answer formatted like this: Sun May 10 2015 21:55:01 GMT-0400 (Eastern Daylight Time)
var d = new Date();
var n = d.toJSON();
will get you the answer formatted the way you were looking for it.
Here is a great explanation of all the ways to manipulate the Date object
I like the dataformat package:
you can install using:
npm i dataformat.
and you can use like that:
dateFormat(medicao.DataHora, 'UTC:HH:MM')

How can I add 1 day to current date?

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');

How to get 30 days prior to current date?

I have a start calendar input box and an end calendar input box. We want defaults start calendar input box 30 days prior to current date and the end calendar input box to be the current date. Here is my date vars.
var today = new Date(),
dd = today.getDate(),
mm = today.getMonth(),
yyyy = today.getFullYear(),
month = ["January", "February", "March",
"April", "May", "June", "July", "August",
"September", "October" "November", "December"],
startdate = month[mm] + ", " + yyyy.toString();
The end date would be something like var enddate = startdate - 30; Obviously this won't work.
So if the current date is December 30, 2011 I'd want the start date to read December 1, 2011.
EDIT: My question was answered... sort of. Date.today(); and Date.today().add(-30); work but I need the date in the format of January 13, 2012. Not Fri Jan 13 2012 10:48:56 GMT -055 (EST). Any help?
MORE EDIT: As of this writing it's 2018. Just use Moment.js. It's the best.
To subtract days from a JS Date object you can use the setDate() method, along with the date to start the calculation from. This will return an epoch timestamp as an integer, so to convert this to a Date you'll need to again provide it to the Date() object constructor. The final example would look like this:
var today = new Date();
var priorDate = new Date(new Date().setDate(today.getDate() - 30));
console.log(today)
console.log(priorDate);
Try using the excellent Datejs JavaScript date library (the original is no longer maintained so you may be interested in this actively maintained fork instead):
Date.today().add(-30).days(); // or...
Date.today().add({days:-30});
[Edit]
See also the excellent Moment.js JavaScript date library:
moment().subtract(30, 'days'); // or...
moment().add(-30, 'days');
Here's an ugly solution for you:
var date = new Date(new Date().setDate(new Date().getDate() - 30));
startDate = new Date(today.getTime() - 30*24*60*60*1000);
The .getTime() method returns a standard JS timestamp (milliseconds since Jan 1/1970) on which you can use regular math operations, which can be fed back to the Date object directly.
Get next 30th day from today
let now = new Date()
console.log('Today: ' + now.toUTCString())
let next30days = new Date(now.setDate(now.getDate() + 30))
console.log('Next 30th day: ' + next30days.toUTCString())
Get last 30th day form today
let now = new Date()
console.log('Today: ' + now.toUTCString())
let last30days = new Date(now.setDate(now.getDate() - 30))
console.log('Last 30th day: ' + last30days.toUTCString())
Javascript can handle it without any external libraries.
var today = new Date();
var dateLimit = new Date(new Date().setDate(today.getDate() - 30));
document.write(today + "<br/>" + dateLimit)
Simple 1 liner Vanilla Javascript code :
const priorByDays = new Date(Date.now() - days * 24 * 60 * 60 * 1000)
For example:
days = 7
Assume current date = Fri Sep 18 2020 01:33:26 GMT+0530
The result would be : Fri Sep 11 2020 01:34:03 GMT+0530
The beauty of this is you can manipulate it to get result in desired type
timestamp : Date.now() - days * 24 * 60 * 60 * 1000
ISOString: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString()
Easy.(Using Vanilla JS)
let days=30;
this.maxDateTime = new Date(Date.now() - days * 24 * 60 * 60 * 1000);
ISOFormat ?
let days=30;
this.maxDateTime = new Date(Date.now() - days * 24 * 60 * 60 * 1000).toISOString();
let today = new Date()
let last30Days = new Date(today.getFullYear(), today.getMonth(), today.getDate() - 30)
last30Days will be in Date Object
I will prefer moment js
startDate = moment().subtract(30, 'days').format('LL') // January 29, 2015
endDate = moment().format('LL'); // February 28, 2015
I use date.js. It handles this easily and takes care of all the leap-year nastiness.
This is an ES6 version
let date = new Date()
let newDate = new Date(date.setDate(date.getDate()-30))
console.log(newDate.getMonth()+1 + '/' + newDate.getDate() + '/' + newDate.getFullYear() )
You can do that simply through 1 line of code using moment in Node JS. :)
let lastOneMonthDate = moment().subtract(30,"days").utc().toISOString()
Don't want UTC format, EASIER :P
let lastOneMonthDate = moment().subtract(30,"days").toISOString()
If you aren't inclined to momentjs, you can use this:
let x = new Date()
x.toISOString(x.setDate(x.getDate())).slice(0, 10)
Basically it gets the current date (numeric value of date of current month) and then sets the value. Then it converts into ISO format from which I slice down the pure numeric date (i.e. 2019-09-23)
Hope it helps someone.
Use moment.js
let startDate = moment().subtract(30, "days").format('YYYY-MM-DD'); //2021-05-18
let endDate = moment().format('YYYY-MM-DD'); //2021-06-17
For anyone looking for the format 'dd month yyyy', here's what worked for me:
let date = new Date()
let newDate = new Date(date.setDate(date.getDate()-30))
console.log(newDate.getDate()+ ' ' +newDate.toLocaleString('default', {month: 'long'}) + ' ' + newDate.getFullYear() )

Categories

Resources