Javascript - Remove year and write full weekday name in date name - javascript

I'd like to use JavaScript to write the date TWO days from now. I'd prefer to show the full weekday name, and not show the year. For example, right now the code I have writes:
"Fri May 08 2020"
and I'd like it to say:
"Friday, May 08"
The script I have is:
<script>
var days = 2;
var newDate = new Date(Date.now() + days * 24*60*60*1000).toDateString();
document.write(newDate);
</script>
Thank you for your help!
Tim

You can do this easily by using Date.prototype.toLocaleString() or Date.prototype.toLocaleDateString() method and passing some parameter to the options object like:
var days = 2;
var newDate = new Date(Date.now() + days * 24 * 60 * 60 * 1000)
.toLocaleDateString(undefined, { weekday: 'long',month: 'long',day: '2-digit' });
document.write(newDate);
//=> Friday, May 08
Few things here:
weekday: 'long' is used to display weekday in long-form like Friday instead of Fri.
day: '2-digit' is used to display date like 08 instead of 8.
You can see without passing these options date will be displayed like:
var days = 2;
var newDate = new Date(Date.now() + days * 24 * 60 * 60 * 1000).toLocaleDateString();
document.write(newDate);
//=> 5/8/2020

Related

Increment date by one day to a set epoch date

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

Javascript - unexpected behavior in dates calculations

I'm a newbie and recently started to read Beginning Javascript, by McPeak and Wilton. The authors propose an exercise about dates calculation. This is the exercise
Using the Date type, calculate the date 12 months from now.
I tried to solve it with this code
//gets today's date
var today = new Date();
//this line transforms the date in milliseconds
var daysAsMilliseconds = 1000* 60 * 60 * 24 * today.getDate();
//creates a new Date object
console.log(new Date(today.setDate(365) + daysAsMilliseconds));
The result I get here is correct(August 11th 2018).
Later, I wonder if it was really necessary to create 2 variables and tried this solution:
var today = new Date();
console.log(new Date(today.setDate(365) + (1000 * 60 * 60 * 24 * today.getDate())));
Here the solution was incorrect. The console showed August 31 2018. Why?
If necessary, here you will find the repl.it with the code
You call setDate, before you call getDate , therefore getDate will always return 365. Simply swapp it:
new Date((1000 * 60 * 60 * 24 * today.getDate()) + today.setDate(365))
Or its may easier to work with months directly:
today.setMonth(today.getMonth() + 12);
var intwelvemonths = today;
All you need to do is add 1 to the year:
var yearFromNow = new Date();
yearFromNow.setYear(yearFromNow.getFullYear() + 1);
Setting the date to 365 makes no sense; .setDate() is for day-of-month, so setting it to that constant moves the date a year (usually) from the last day of the previous month. And you don't need to do any other math outside of the date API; just increment the year, and you're done.
You're calling today.setDate(365) before you're adding the results of today.getDate(): today.getDate() will give the date that you set, not today's date.
Changing the order of operations will do the trick:
var today = new Date();
new Date((1000 * 60 * 60 * 24 * today.getDate()) + today.setDate(365));
I recommend you to use a package as moment.js because it manage a lot of date formats, and it has very good implementations for date managing.
Using moment js for add.
moment().add(Number, String);
Example
var m = moment(new Date(2011, 2, 12, 5, 0, 0));
m.hours(); // 5
m.add(1, 'days').hours(); // 5
For more docs see moment().add() docs

Calculate Date with start date and number of days with javascript

I am trying to calculate a date from a start date and number of days, so basicly add the number of days to a start date and get an end date. The issue is I get some strange results, but only on one date, I have been a few days now trying to figure this one out.
The function is:
CallculateDateFromDays = function(startDate, days) {
var policy_start_date_array = startDate.split("-");
var policy_start_date = new Date(policy_start_date_array[2], policy_start_date_array[1]-1, policy_start_date_array[0]);
var policy_start_date_add = new Date(policy_start_date.getTime() + ((days-1) * 24 * 60 * 60 * 1000));
var dateString = ("0" + (policy_start_date_add.getDate())).slice(-2) + "-" + ("0" + (policy_start_date_add.getMonth()+1)).slice(-2) + "-" + policy_start_date_add.getFullYear();
return dateString;}
The thing is it works until I use the date "28-10-2012" it gives me back the same date even if I add 2 days.
Any ideas, I am stumped.
Likely your local timezone changes because of the end of the daylight saving time.
> new Date(2012, 9, 28)
Sun Oct 28 2012 00:00:00 GMT+0200
> // 48 hours later:
> new Date(new Date(2012, 9, 28) + 2 * 24 * 60 * 60 * 1000)
Mon Oct 29 2012 23:00:00 GMT+0100
Always use the UTC methods!
BTW, adding days is much more easier with setDate, which also works around timezone issues:
function calculateDateFromDays(startDate, days) {
var datestrings = startDate.split("-"),
date = new Date(+datestrings[2], datestrings[1]-1, +datestrings[0]);
date.setDate(date.getDate() + days);
return [("0" + date.getDate()).slice(-2), ("0" + (date.getMonth()+1)).slice(-2), date.getFullYear()].join("-");
}
On October 28th the time changes from DST to "normal", so the day is not equal 24h. That may cause issues in your code.
Also why (days-1) * 24 * 60 * 60 * 1000? If you set days to 1 the whole expression evaluates to zero...
There's an easier way to achieve that :
http://jsfiddle.net/pjambet/wZEFe/2/
Use javascript date format:
How to format a JavaScript date
So you don't have to manually try to parse date strings.

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