add days to current date in javascript [duplicate] - javascript

This question already has answers here:
How can I add 1 day to current date?
(10 answers)
Closed 5 years ago.
I am currently using this formula to populate the current date into a fillable PDF for work:
var f = this.getField("Today");
f.value = util.printd("mm/dd/yyyy", new Date());
This fillable PDF is a government document and once it's printed expires in 45 days including the date printed. Like a Temp Tag for a vehicle.
How do I add 44 days to this formula so that it automatically kicks out 45 days down the road?

Here is what you wanna do:
var laterDate = new Date(); // create new Date object set to current date
laterDate.setDate(laterDate.getDate() + 44); // add 44 days
then you could use your util library and display it:
util.printd("mm/dd/yyyy", laterDate);

For handling dates in JavaScript, you could use Moment.js. With moment you can perform a wide range of operations on dates and time. Check it's docs for more info. As for your query, you could do
moment().add(44, 'days');

Related

Get current week and date of week in react native [duplicate]

This question already has answers here:
Get week of the month
(17 answers)
Closed 2 years ago.
I need to display a whole week from Monday To Sunday in following format "Week 2: 05.01 - 11.01" as an example
let d = new Date();
let date = d.getDate();
let day = d.getDay();
let currentWeek = Math.ceil((date + 6 - day) / 7);
this is what i have for the current week, i know that it will have some issues if the previous month is in the first week of the current month.
Any help as to how to make it accurate and reliable?
I need it to work in React Native!
I like using moment to deal with Dates, since date operations are somewhat complex considering month changes, leap years and all that.
Using moment, you'd just need to do
const today = moment();
const begginingOfCurrentWeek = today.startOf('week');
const endOfWeek = today.endOf('week);
I havent tested it, but it should be something along those lines. You can also format dates easily using moment().format('DD/MM/YY'), for example.
Here's the link to their documentation:
https://momentjs.com/

mySql Timestamp Display Conversion [duplicate]

This question already has answers here:
How do I format a date in JavaScript?
(68 answers)
Parsing a string to a date in JavaScript
(35 answers)
Closed 2 years ago.
I have a table where one of the columns is entered as CURRENT_TIMESTAMP.
I am pulling the data from the table and displaying it on my site. But can't figure out how to convert the date into a more reader friendly format.
Right now it looks like this: 2020-09-17T19:56:24.000Z (I also need to figure out how to convert to my timezone.)
But I want it to display like this: 09-17-2020 19:56 (would even prefer 07:56pm, but not critical)
I've seen a few examples where you can reformat it during the query. But all the examples I've seen are pulling just the date. I'm pulling everything. I'm fine with running a function on it after the query to convert... but I haven't been able to figure it out.
You could use a simple function using the built-in methods available to Date objects in js. Something like this is probably what you're looking for.
function formatDate(date){
const month = date.getUTCMonth()+1;
const day = date.getUTCDate();
const year = date.getUTCFullYear();
const hours = d.getUTCHours() > 12 ? d.getUTCHours() - 12 : d.getUTCHours();
const minutes = d.getUTCMinutes();
return `${month}-${day}-${year} ${hours}:${minutes}`}

Javascript Subtract/Add 1 month from date [duplicate]

This question already has answers here:
JavaScript function to add X months to a date
(24 answers)
Adding months to a Date in JavaScript [duplicate]
(2 answers)
Closed 2 years ago.
I'm trying to find a method that reliably subtracts 1 month from a javascript date object.
I have this code:
var shippedDate = new Date('12/31/2020');
var tempDate = new Date(shippedDate.setMonth(shippedDate.getMonth() - 1)); //subtract 1 month
alert(tempDate);
The value in tempDate after this code runs is 12/1/2020 when it should actually be 11/30/2020.
I checked my math with this online date calculator: https://www.timeanddate.com/date/dateadded.html?m1=12&d1=31&y1=2020&type=sub&ay=&am=1&aw=&ad=&rec=
Thanks.
December has 31 days so when you subtract 1 month, you get 31 November which doesn't exist, so it rolls over to 1 December.
You can test the date (day in month) to see if it's the same, and if not, set the date to 0 so it goes to the last day of the previous month.
Also, setDate modifies the Date object so no need to create a new one:
function subtractMonth(date, months) {
let d = date.getDate();
date.setMonth(date.getMonth() - months);
if (date.getDate() != d) {
date.setDate(0);
}
return date;
}
let d = new Date(2020, 11, 31); // 31 Dec 2020
console.log(subtractMonth(d, 1).toString()); // 30 Nov 2020
This has side effects so that sequentially subtracting 2 months may give a different result to subtracting 2 months in one go.
Also in regard to new Date('12/31/2020'), see see Why does Date.parse give incorrect results?
PS
I answered this before I remembered that there were plenty of questions about adding months that also cover subtracting. So I marked this question as a duplicate and rather than delete this answer, left it for posterity.
If you wish to vote for an answer, please go to one of the duplicates and vote for an answer there. :-)
On my own experience, I may qualify all around Date calculation in javascript as completely unbearable pain.
Avoid as possible own crafted function to any Date manipulation. There are too many traits to lose mind at all. Timezones, wrong clocks, timezone on your own host vs. timezone on server, unexpected toString conversion according to local host timezone/clock.
If you rally need to make some dates calculation use battle tested library, like date-fns, moment.js, etc.
By the way your example almost correct, you just have chosen not suitable time to try to test it. The only one that I see problematic it's using setMonth that mutate original shippedDate.

Javascript: Get epoch date as from predefined date is using todays date instead [duplicate]

This question already has answers here:
Convert UNIX to readable date in javascript
(3 answers)
Closed 4 years ago.
JSFiddle: https://jsfiddle.net/u8w3v9fd/1/
I am trying to get the day, month and year from a date that is passed form the database in the format: DD/MM/YYYY. However I can't even seem to get the correct date to show.
Here is my code:
var time = "1522843537";
var regDateOriginal = new Date(time);
var regDate = new Date();
regDate.getMonth(regDateOriginal);
regDate.getHours(regDateOriginal);
regDate.getDate(regDateOriginal);
document.write("<p style='color: #fff'>" + regDate.getDate(regDateOriginal) + "</p>");
As you can see, this is returning:
21
Which is todays date. It should be 4
I have googled it and hacked around with various versions for the past 45 mins. I am a junior and would really appreciated a nicely commented piece of code so I can learn instead of just copying and pasting.
Thank you for your help.
From here
var time = 1522843537;
var d = new Date(0); // The 0 there is the key, which sets the date to the epoch
d.setUTCSeconds(time);
console.log(d.getDate());
Of course, you can still do all the other Date functions as needed.

Get number of days prior to the specified date Javascript [duplicate]

This question already has answers here:
Date difference in Javascript (ignoring time of day)
(15 answers)
How to subtract days from a plain Date?
(36 answers)
Closed 6 years ago.
I'm reading the value of the date input and need to workout if there is 42 days or more between the specified date and today's date. This is what I've tried so far:
var sdate = new Date($("#holiday-editor input[name=StartDate]").val()); //This is returing date in the string format
var priorDate = new Date().setDate(sdate - 42).toString(); // This is returning some abstract int value
var dateNow = new Date().getDate().toString(); // this is returning 5 even though I'd like to get today's date in the string format
if (dateNow > priorDate) {
$("#HolidayBookedLate").show();
}
If you manipulate dates a lot in your app I'd suggest to use moment.js. It's only 15kb but it has lots of useful features to work with dates.
In your case you can use diff function to get amount of days between two dates.
var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b, 'days') // 1

Categories

Resources