Calculate javascript date [duplicate] - javascript

This question already has answers here:
How to add number of days to today's date? [duplicate]
(16 answers)
Closed 8 years ago.
i have the date 2013-12-28 and i want add one or more more day to it. so if i add one more day it will be 2013-12-29.
i try to add it by adding the value of it's date (date 28+1), it works, but what if i add 7 more day to it? the date will be 35, and of course it is not a valid date format.
can someone help me?
here's the example of my script:
var d = new Date();
var Y = d.getFullYear();
var M = d.getMonth()+1;
var D = d.getDate();
var DT = d.getDate()+1;// what if i + 20 days from today? the format would be invalid
var today = Y+"-"+M+"-"+D;
var tomorrow = Y+"-"+M+"-"+DT;
alert(today+" <> "+tomorrow);
// "<>" means nothing

You may try like this using getdate(), setdate() and getdate():
var myDate = new Date();
myDate.setDate(myDate.getDate() + 7);

If you already have a date object as in the code you show:
var d = new Date();
...then you can add 7 days to it like this:
d.setDate( d.getDate() + 7 );
...and it will automatically increment the month if needed.
Further reading:
The Date object
.getDate() method
.setDate() method
If you need to extract the year, month and day in order to format the result a particular way do so after adding days.

The solution is to convert your date string into unix timestamp, and them add 3600 * 24 * <number of days> to the timestamp and them convert it back to date string.
The code can be as follows:
function addDaysToDate(date, days) {
var time = Date.parse(date) + days * 24 * 3600;
date = new Date(time);
return date.getFullYear() + '-' + date.getMonth() + '-' + date.getDate();
}
var date = '2013-12-28';
console.log(addDaysToDate(date, 7));

Related

Unable to understand the date format which i am receiving from API response? [duplicate]

This question already has answers here:
Convert a Unix timestamp to time in JavaScript
(34 answers)
How do I format a date in JavaScript?
(68 answers)
Closed last year.
How to convert this timestamp 1382086394000 to 2013-10-18 08:53:14 using a function in javascript? Currently I have this function:
function cleanDate(d) {return new Date(+d.replace(/\/Date\((\d+)\)\//, '$1'));}
The value 1382086394000 is probably a time value, which is the number of milliseconds since 1970-01-01T00:00:00Z. You can use it to create an ECMAScript Date object using the Date constructor:
var d = new Date(1382086394000);
How you convert that into something readable is up to you. Simply sending it to output should call the internal (and entirely implementation dependent) toString method* that usually prints the equivalent system time in a human readable form, e.g.
Fri Oct 18 2013 18:53:14 GMT+1000 (EST)
In ES5 there are some other built-in formatting options:
toDateString
toTimeString
toLocaleString
and so on. Note that most are implementation dependent and will be different in different browsers. If you want the same format across all browsers, you'll need to format the date yourself, e.g.:
alert(d.getDate() + '/' + (d.getMonth()+1) + '/' + d.getFullYear());
* The format of Date.prototype.toString has been standardised in ECMAScript 2018. It might be a while before it's ubiquitous across all implementations, but at least the more common browsers support it now.
This works fine. Checked in chrome browser:
var theDate = new Date(timeStamp_value * 1000);
dateString = theDate.toGMTString();
alert(dateString );
why not simply
new Date (timestamp);
A date is a date, the formatting of it is a different matter.
Moment.js can convert unix timestamps into any custom format
In this case : var time = moment(1382086394000).format("DD-MM-YYYY h:mm:ss");
will print 18-10-2013 11:53:14;
Here's a plunker that demonstrates this.
Here are the simple ways to every date format confusions:
for current date:
var current_date=new Date();
to get the Timestamp of current date:
var timestamp=new Date().getTime();
to convert a particular Date into Timestamp:
var timestamp_formation=new Date('mm/dd/yyyy').getTime();
to convert timestamp into Date:
var timestamp=new Date('02/10/2016').getTime();
var todate=new Date(timestamp).getDate();
var tomonth=new Date(timestamp).getMonth()+1;
var toyear=new Date(timestamp).getFullYear();
var original_date=tomonth+'/'+todate+'/'+toyear;
OUTPUT:
02/10/2016
we need to create new function using JavaScript.
function unixTime(unixtime) {
var u = new Date(unixtime*1000);
return u.getUTCFullYear() +
'-' + ('0' + u.getUTCMonth()).slice(-2) +
'-' + ('0' + u.getUTCDate()).slice(-2) +
' ' + ('0' + u.getUTCHours()).slice(-2) +
':' + ('0' + u.getUTCMinutes()).slice(-2) +
':' + ('0' + u.getUTCSeconds()).slice(-2) +
'.' + (u.getUTCMilliseconds() / 1000).toFixed(3).slice(2, 5)
};
console.log(unixTime(1370001284))
2016-04-30 08:36:26.000
This is what I did for the Instagram API. converted timestamp with date method by multiplying by 1000.
and then added all entity individually like (year, months, etc)
created the custom month list name and mapped it with getMonth() method which returns the index of the month.
convertStampDate(unixtimestamp){
// Months array
var months_arr = ['January','February','March','April','May','June','July','August','September','October','November','December'];
// Convert timestamp to milliseconds
var date = new Date(unixtimestamp*1000);
// Year
var year = date.getFullYear();
// Month
var month = months_arr[date.getMonth()];
// Day
var day = date.getDate();
// Hours
var hours = date.getHours();
// Minutes
var minutes = "0" + date.getMinutes();
// Seconds
var seconds = "0" + date.getSeconds();
// Display date time in MM-dd-yyyy h:m:s format
var fulldate = month+' '+day+'-'+year+' '+hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);
// final date
var convdataTime = month+' '+day;
return convdataTime;
}
Call with stamp argument
convertStampDate('1382086394000')
and that's it.
Use .toLocaleString:
// undefined uses default locale
console.log(new Date().toLocaleString(undefined, {dateStyle: 'short'}));
Or custom method in case you don't want to use the toLocaleString for some reason:
formatDate is the function you can call it and pass the date you want to format to dd/mm/yyyy
var unformatedDate = new Date("2017-08-10 18:30:00");
$("#hello").append(formatDate(unformatedDate));
function formatDate(nowDate) {
return nowDate.getDate() +"/"+ (nowDate.getMonth() + 1) + '/'+ nowDate.getFullYear();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="hello">
</div>
My ES6 variant produces a string like this 2020-04-05_16:39:45.85725. Feel free to modify the return statement to get the format that you need:
const getDateStringServ = timestamp => {
const plus0 = num => `0${num.toString()}`.slice(-2)
const d = new Date(timestamp)
const year = d.getFullYear()
const monthTmp = d.getMonth() + 1
const month = plus0(monthTmp)
const date = plus0(d.getDate())
const hour = plus0(d.getHours())
const minute = plus0(d.getMinutes())
const second = plus0(d.getSeconds())
const rest = timestamp.toString().slice(-5)
return `${year}-${month}-${date}_${hour}:${minute}:${second}.${rest}`
}
There is a simple way to convert to a more readable form
new Date().toLocaleString();
new Date(1630734254000).toLocaleString();
Outputs in this format => 9/4/2021, 11:14:14 AM
new Date(timestamp).toString().substring(4, 15)
1631685556789 ==> Sep 15 2021
To calculate date in timestamp from the given date
//To get the timestamp date from normal date: In format - 1560105000000
//input date can be in format : "2019-06-09T18:30:00.000Z"
this.calculateDateInTimestamp = function (inputDate) {
var date = new Date(inputDate);
return date.getTime();
}
output : 1560018600000

I am Working on Javascript Dates, i am stuck with adding 7 days to a date [duplicate]

This question already has answers here:
How to add days to Date?
(56 answers)
Closed 2 years ago.
var date = new Date();
var first_date = new Date(date); //Make a copy of the date we want the first and last days from
first_date.setUTCDate(1); //Set the day as the first of the month
var firstDay = first_date.toJSON().substring(0, 10);
console.log(firstDay)
I am Working on Javascript Dates, i am stuck with adding 7 days to this date
Thanks in advance
var date = new Date();
var first_date = new Date(date); //Make a copy of the date we want the first and last days from
first_date.setUTCDate(1); //Set the day as the first of the month
var firstDay = first_date.toJSON().substring(0, 10);
var resultDate = new Date();
resultDate.setDate(first_date.getDate() + 7);
var resultDay = resultDate.toJSON().substring(0, 10);
console.log("First day: " + firstDay)
console.log("7 days from specific day: " + resultDay)

Get previous month date javascript [duplicate]

This question already has answers here:
How to get 30 days prior to current date?
(16 answers)
Closed 7 years ago.
How can I get previous month date in javascript. Suppose you have today's date like:
var abc = new date();
It will return today's date for example 03-11-2015. Now I want to get 03-10-2015. This is 30 days less than todays date. How can I do this?
var d = new Date();
d.setMonth(d.getMonth() - 1);
Check out momentjs, great little library for manipulating and formatting dates.
Complementing Robert Shenton's answer:
var d = new Date();
var newMonth = d.getMonth() - 1;
if(newMonth < 0){
newMonth += 12;
d.setYear(d.getFullYear() - 1); // use getFullYear instead of getYear !
}
d.setMonth(newMonth);

Get difference in months and list the months in an array between two dates in javascript

I'm having two dates given below with the format for which I need to get the number of months that are there in between them.I tried Difference in months between dates in Javascript :
but the format is not matching with the one that I have.Can anybody suggest a fix please?
startDate:"2015-09-07",
endDate: "2015-12-30"
Also I need to display the months that are there in between the dates like:
var months=["sept","oct","nov","dec","jan","feb"]
Well, you could always split string and use month like this:
var startDate = startDate.split("-");
var endDate= endDate.split("-");
var MonthDifference = endDate[1] - startDate[1];
So you could for example do this function:
function DifferenceInMonths(startDate, endDate){
startDate= startDate.split("-");
endDate= endDate.split("-");
return endDate[1] - startDate[1];
}
But then we are facing problem where these dates could happen in 2 different years. What if you would try this:
function differenceCalculatedInMonthsByUnix(startDate, endDate){
startDate = new Date(startDate).getTime();
endDate= new Date(endDate).getTime();
var difference = endDate - startDate;
return timeMe(difference);
}
function timeMe(unix_timestamp){
unix_timestamp = parseInt(unix_timestamp);
var date = new Date(unix_timestamp);
var days = date.getDate();
var month = date.getMonth() + 1;
var year = date.getFullYear()
// hours part from the timestamp
var hours = date.getHours();
// minutes part from the timestamp
var minutes = "0" + date.getMinutes();
// seconds part from the timestamp
var seconds = "0" + date.getSeconds();
// will display time in 10:30:23 format
var formattedTime = days + '.' + month + '.' + year + ' at:' + hours + ':' + minutes.substr(minutes.length-2) + ':' + seconds.substr(seconds.length-2);
return (12 * year) + month
}
Not sure did i do that TimeMe() my self or did i find it from stackOverflow so if some one needs credits, pm me.
But yea the idea in this is, that we turn date into unix time stamp, calculate difference, and turn it into months.

Get last day of the month from '2015-02-23' string (javascript) [duplicate]

This question already has answers here:
Get number days in a specified month using JavaScript? [duplicate]
(4 answers)
Closed 8 years ago.
I have a string that represents a date in this format: 2015-02-23
I need to use this date to get the last day of the month.
How should I do the necessary conversions to achieve that?
Here's a function that should work for you:
function getLastDayInMonth(s) {
var date = new Date(s);
var lastDate = date;
var month = date.getMonth();
while (date.getMonth() == month) {
lastDate = date;
date = new Date(lastDate.getTime() + 1000 * 60 * 60 * 24); //add 1 day
}
return lastDate.toDateString();
}
var lastDay = getLastDayInMonth('2015-02-23');
alert(lastDay);

Categories