add 12 months for Now Date - javascript

Hi, I would like to add 12 months and subtract 1 day for my current
date.
Example :
valStartDate :2018-01-20
expected_date:2019-01-19
I try below code but error "getFullYear() not a function to allow"
this.endDate =this.valStartDate.getFullYear()+1+'-'+this.valStartDate.getMonth()+'-'+(this.valStartDate.getDate()-1);

Ensure that your given start date is a date and not a string.
var startDate = new Date(2018, 0, 20);
var startDatePlus12Months = new Date(startDate.setMonth(startDate.getMonth() + 12));
var expectedDate = new Date(startDatePlus12Months.getFullYear(), startDatePlus12Months.getMonth(), startDatePlus12Months.getDate() - 1);

Here is a method of abstracting the date you want, apply this the variable and you should be good to go.
var date = new Date(); // now
var newDate = new Date(date.getFullYear() + 1, date.getMonth(), date.getDate() - 1);
console.log(newDate.toLocaleDateString());
this.valStartDate.getFullYear() In order for this to work, this.valStartDate must be a valid javascript date and look the same format as new Date(); would give you.
Fri Apr 26 2019 11:52:15 GMT+0100 (British Summer Time)

this.endDate = new Date(this.endDate); // <= maybe you get a string date...
this.endDate.setMonth(this.endDate.getMonth() + 12);
this.endDate.setDate(this.endDate.getDate() - 1);
If you're getting your date from a server or from a previous Json format, maybe you need to convert it from string to Date first: this.endDate = new Date(this.endDate);. It seems this is your case.

This is easy with the help of Moment.js:
const startDate = moment('2018-01-20');
const endDate = startDate.add(12, 'months').subtract(1, 'days').toDate();

Related

How to get time using toDate() and not format() [duplicate]

how can i extract time from datetime format.
my datetime format is given below.
var datetime =2000-01-01 01:00:00 UTC;
I only want to get the time 01.00 as 01
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleTimeString
Date.prototype.toLocaleTimeString()
Returns a string with a locality sensitive representation of the time portion of this date based on system settings.
var time = datetime.toLocaleTimeString();
Update:
The new locales and options arguments let applications specify the
language whose formatting conventions should be used and customize the
behavior of the function. In older implementations, which ignore the
locales and options arguments, the locale used and the form of the
string returned are entirely implementation dependent.
// Depending on timezone, your results will vary
var event = new Date('August 19, 1975 23:15:30 GMT+00:00');
console.log(event.toLocaleTimeString('en-US'));
// expected output: 1:15:30 AM
console.log(event.toLocaleTimeString('it-IT'));
// expected output: 01:15:30
What about these methods
new Date().getHours()
new Date().getMinutes()
For example:
var d = new Date();
var n = d.getHours();
Edited
Return the hour, according to universal time:
new Date().getUTCHours()
Example:
var d = new Date();
var n = d.getUTCHours();
As an alternative if you want to get the time from a string -
var datetime ="2000-01-01 01:00:00 UTC";
var myTime = datetime.substr(11, 2);
alert(myTime) //01
with the moment.js library it works in this way:
var result = moment().format('hh');
alert(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>
var datetime = ("2000-01-01 01:00:00 UTC");
var d1 = new Date(datetime);
var minute = d1.getUTCMinutes();
var hour = d1.getUTCHours();
if(minute > 0)
alert(hour+"."+minute);
else
alert(hour);
Demo
var date1 = new Date(1945,10,20, 17,30)
var date2 = new Date(1970,1,8, 12,00)
console.log(date1.getHours() - 8 + (date1.getMinutes()/60))
console.log(date2.getHours() - 8 + (date2.getMinutes()/60))
Use the following code:
var datetime = "2000-01-01 01:00:00 UTC";
var dt = new Date(datetime);
var hr = dt.getUTCHours();
if(hr > 12) {
hr -= 12;
}
alert(hr);
refer this link also.
I have done it! It looks like this:
console.log(new Date().toLocaleTimeString() + " " + new Date().getSeconds() + " seconds");
Assuming you have a Date object like
var datetime = new Date("2000-01-01 01:00:00 UTC"); // might not parse correctly in every engine
// or
var datetime = new Date(Date.UTC(2000, 0, 1, 1, 0, 0));
then use the getUTCHours method:
datetime.getUTCHours(); // 1
I hope you can find a solution here.
let preDateTime = new Date("2022-03-31 22:26:00");
let newTime = preDateTime.toLocaleTimeString('en-US');
let hour = newTime.split(":")[0];
let amPm = newTime.split(" ")[1];
let seconds = newTime.split(":")[2].replace(amPm,'');;
let noAmPm = newTime.replace(amPm,'');
let noAmPmSeconds = noAmPm.replace(":"+seconds,'');
let noSeconds = newTime.replace(":"+seconds,' ');
if(parseInt(hour)<9){
newTime = "0"+newTime;
noAmPm = "0"+noAmPm
noSeconds= "0"+noSeconds
noAmPmSeconds = "0"+noAmPmSeconds;
}
console.log(newTime); //10:26:00 PM
console.log(noAmPm); //10:26:00
console.log(noSeconds); //10:26 PM
console.log(noAmPmSeconds); //10:26

Display the tomorrow's date

I'm trying to create a JS code which displays tthe tomorrow's date.
This is the code I tried :
var d = new Date.today().addDays(1).toString("dd-mm-yyyy");
but it won't work for me.
How can I solve it ?
var todayDate = new Date();
todayDate .setDate(todayDate .getDate() + 1);
Then todayDate contains tomorrow date
Try this :
var d = new Date();
var tomorrowDate = d.getDate() + 1;
d.setDate(tomorrowDate);
document.write("Tommorow date : " + d );
Output :
Tommorow date : Fri Jul 05 2013 19:16:50 GMT+0530 (IST)
var d = new Date();
d.setDate(d.getDate() + 1)
console.log(d)
If you're going to deal a lot with dates, I'd recommend you to use Moment.js. It allows you to do exactly what you want, aswell much more things:
var date = moment().add("days", 1);
// If displaying this date, use the following to format it in your culture.
// Will be mm-dd-yyyy in en-US, I believe
date.format("L");
Docs: http://momentjs.com/docs/

compare 2 dates by combining date and time

var dateStart = $('input[id=orderdate-0]').val();
var timeStart = $('input[id=ordertime-0]').val();
var dateEnd = $('input[id=orderdate-1]').val();
var timeEnd = $('input[id=orderime-1]').val();
var startDate = new Date(dateStart + " " + timeStart);
var endDate = new Date(dateEnd + " " + timeEnd);
startDate.getTime();
alert(startDate);
i am trying to combine dateStart which is '2013-12-11' and timeStart which is '11:00' and trying to generate date out of it. But i get alert like invalid date. Is there anything wrong in code.?
The Date constructor is very particular about the date string formats it accepts.
Examples:
Dec 25, 1995
Wed, 09 Aug 1995 00:00:00
2011-10-10T14:48:00 (JavaScript 1.8.5+)
There is another constructor that take in the individual components of the date. If you break up your date strings into components you can use the following:
new Date(year, month, day, hour, minute);
Use moment JS plugin http://momentjs.com/
It's a date library for parsing, validating, manipulating, and formatting dates.
That is not a valid format for the parse function, you can use this instead:
var arr = dateStart.split('-');
var timeArr = timeStart.split(':');
new Date(arr[0], arr[1] -1, arr[2], timeArr[0] -1, timeArr[1] -1);
Read this.
Live DEMO

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

Concatenate a date and time value

i need to concatenate a date value and a time value to make one value representing a datetime in javascript.
thanks,
daniel
Working with strings is fun and all, but let's suppose you have two datetimes and don't like relying on strings.
function combineDateWithTime(d, t)
{
return new Date(
d.getFullYear(),
d.getMonth(),
d.getDate(),
t.getHours(),
t.getMinutes(),
t.getSeconds(),
t.getMilliseconds()
);
}
Test:
var taxDay = new Date(2016, 3, 15); // months are 0-indexed but years and dates aren't.
var clockout = new Date(0001, 0, 1, 17);
var timeToDoTaxes = combineDateWithTime(taxDay, clockout);
// yields: Fri Apr 15 2016 17:00:00 GMT-0700 (Pacific Daylight Time)
I could not make the accepted answer work so used moment.js
date = moment(selected_date + ' ' + selected_time, "YYYY-MM-DD HH:mm");
date._i "11-06-2014 13:30"
Assuming "date" is the date string and "time" is the time string:
// create Date object from valid string inputs
var datetime = new Date(date+' '+time);
// format the output
var month = datetime.getMonth()+1;
var day = datetime.getDate();
var year = datetime.getFullYear();
var hour = this.getHours();
if (hour < 10)
hour = "0"+hour;
var min = this.getMinutes();
if (min < 10)
min = "0"+min;
var sec = this.getSeconds();
if (sec < 10)
sec = "0"+sec;
// put it all togeter
var dateTimeString = month+'/'+day+'/'+year+' '+hour+':'+min+':'+sec;
Depending on the type of the original date and time value there are some different ways to approach this.
A Date object (which has both date and time) may be created in a number of ways.
birthday = new Date("December 17, 1995 03:24:00");
birthday = new Date(1995,11,17);
birthday = new Date(1995,11,17,3,24,0);
If the original date and time also is objects of type Date, you may use getHours(), getMinutes(), and so on to extract the desired values.
For more information, see Mozilla Developer Center for the Date object.
If you provide more detailed information in your question I may edit the answer to be more specific.

Categories

Resources