How to keep original date format after manipulation? - javascript

I have a reference date like this :
2018-05-23T17:02:59+02:00
I need to substract 1 (milli)second from this reference date, then return it on the exact same format, like this :
2018-05-23T17:02:58+02:00
I succeeded going to the previous second of the same date like this :
var refTime = '2018-05-23T17:02:59+02:00';
var d = new Date(refTime);
var nd = d.setMilliseconds(-1);
But I can't find how to output nd on the exact same format as refTime.
How could I do ?

UPDATE: Just substract 1 to the date.
// 1ms difference
d.getMilliseconds() // 999
newdate2.getMilliseconds() // 998
var refTime = '2018-05-23T17:02:59+02:00';
var d = new Date(refTime);
var nd = d.setMilliseconds(-1);
// new date
var newdate = new Date(d - 1);
console.log(newdate);

//Get second and set subtracting a second
var refTime = '2018-05-23T17:02:59+02:00';
var d = new Date(refTime);
var nd = d.setSeconds(d.getSeconds() - 1);
console.log(new Date(nd))

//Using moment js
var refTime = '2018-05-23T17:02:59+02:00';
var d = new moment(refTime);
var nd = d.subtract(1, 'seconds')
console.log(new moment(nd))
<script src="https://momentjs.com/downloads/moment.min.js"></script>

Related

Calculate age in JS given the birth date in "dd/mm/yyyy" format

I am trying to write a function in JavaScript to calculate age.
I wrote a function but it does not give accurate age.
function calculateAge(date) {
var formattedDate = date.split("/")
var birthdateTimeStamp = new Date(formattedDate[2], [1], formattedDate[0])
var currentDate = new Date().getTime();
var difference = currentDate - birthdateTimeStamp;
var currentAge = Math.floor(difference / 31557600000)
// dividing by 1000*60*60*24*365.25
return currentAge
}
I try calculateAge("25/11/1993") and I don't get accurate age. Kindly guide me.
You missed the formattedDate for [1] in the new Date() function, so formattedDate[1] it should be.
function calculateAge(date) {
var formattedDate = date.split("/")
var birthdateTimeStamp = new Date(formattedDate[2], formattedDate[1], formattedDate[0])
var currentDate = new Date().getTime();
var difference = currentDate - birthdateTimeStamp;
var currentAge = Math.floor(difference / 31557600000)
// dividing by 1000*60*60*24*365.25
return currentAge
}
var age = calculateAge('25/11/1993');
console.log('My age is', age);

How to check if the date having more than one year from current year

I am trying to check if the date i.e. (07/02/2018 ) is more than year from current date and if the date i.e. (07/02/2018 ) is less than year from current date using JavaScript tried with following code
var x = new Date('JUN-2016');
var y = new Date('MAY-2016');
console.log(+x < +y);
Your question is not very clear to me but this may help you:
var now = new Date();
var then = new Date('07/02/2018');
var diffInDays = Math.round((then-now) / (1000*60*60*24));
console.log('then is', diffInDays, 'days more than now.');
Note: If diffInDays is a positive number then the then is more than now, otherwise it's less.
You can simply add 1000*60*60*24*365 milliseconds to your first date and compare it to your second date :
var x = new Date('APR-2015');
var y = new Date('MAY-2016');
console.log(+x + 1000*60*60*24*365 < +y);
var x2 = new Date('SEP-2015');
console.log(+x2 + 1000*60*60*24*365 < +y);
You can get the year with the getFullYear()method (Date doc).
let x = new Date();
let y = new Date();
x_year = x.getFullYear();
y_year = y.getFullYear();
// The you just have to compare the year
One way to do it, although I'd be surprised if there wasn't a better way:
var x = new Date();
x = x.setFullYear(x.getFullYear() + 1);
x = new Date(x);
var y = (new Date('2018-04-08'));
var z = (new Date('2019-04-08'));
if (y < x) {
console.log('Y is less than a year from now');
} else {
console.log('Y is more or exactly a year from now');
}
if (z < x) {
console.log('Z is less than a year from now');
} else {
console.log('Z is more or exactly a year from now');
}
Your question is not clear this is based on my assumption.
I am assuming that you need to check if the given date is one year ahead of the current date.
var x = new Date('1, 1, 2018');
var today = new Date();
var time = Math.abs(today.getTime() - x.getTime());
var days = Math.ceil(time / (1000 * 3600 * 24));
alert("There is a difference of " + days + " days between today and the given date");
I am assuming that you want to know if some arbitrary date is less or more than a year from current date.
We can get a the value for a year this way:
var a_year = Math.abs(new Date('01-01-2018'.replace(/-/g,'/')) - new Date('01-01-2017'.replace(/-/g,'/')));
Then we set two date tests:
var test1 = '01-01-2018';
var test2 = '01-01-2015';
Calculate the diffs:
var diff1 = Math.abs(new Date() - new Date(test1.replace(/-/g,'/')));
var diff2 = Math.abs(new Date() - new Date(test2.replace(/-/g,'/')));
Then you can log the results for testing:
console.log(diff1 > a_year)
console.log(diff1 < a_year)
console.log(diff2 > a_year)
console.log(diff2 < a_year)
Credits to David Hedlund's answer on How to subtract date/time in javascript?

Get Diffrence between two date string in momentjs?

I am using momentjs for date and I have one date string, ie,"2015-05-10",I want to get date difference from today
var today= moment().format('YYYY-MM-DD');
How it is possible here?
here is a example,
var now = moment(); // moment object of now
var day = moment("2015-05-13"); // moment object of other date
$scope.difference = now.diff(day, 'days'); // calculate the difference in days
$scope.difference = now.diff(day, 'hours'); // calculate the difference in hours
check more options here
here is a example
You can use diff
//Convert to date
var today = moment();
var date = moment("2015-05-13", "YYYY-MM-DD");
//Use diff
var duration = today.diff(date);
var hours = duration.asHours();
if you are talking about time difference in hours
var now = "04/09/2013 15:00:00";
var then = "02/09/2013 14:20:30";
var ms = moment(now,"DD/MM/YYYY HH:mm:ss").diff(moment(then,"DD/MM/YYYY HH:mm:ss"));
var d = moment.duration(ms);
var s = Math.floor(d.asHours()) + moment.utc(ms).format(":mm:ss");

Date is considering 31 days of month

While working with date difference, when I am using below code somehow function is assuming that all the months have 31 days. For ex. if I am subtracting 01-March with 28-February the difference is coming as 4 days. Is there any simple way to twick this. Any help will be appreciated.
function myFunction()
{
var sysdt = "02/28/2013";
var year = sysdt.substring(6,10);
var mon = sysdt.substring(0,2);
var date = sysdt.substring(3,5);
var n = Date.UTC(year,mon,date);
var userdt = "03/01/2013"
var yr = userdt.substring(6,10);
var mn = userdt.substring(0,2);
var dd = userdt.substring(3,5);
var n1 = Date.UTC(yr,mn,dd);
var x = document.getElementById("demo");
x.innerHTML=(n1-n)/(1000*24*60*60);
}
This will give you the difference between two dates, in milliseconds
var diff = Math.abs(date1 - date2);
example, it'd be
var diff = Math.abs(new Date() - compareDate);
You need to make sure that compareDate is a valid Date object.
Something like this will probably work for you
var diff = Math.abs(new Date() - new Date(dateStr.replace(/-/g,'/')));
i.e. turning "2011-02-07 15:13:06" into new Date('2011/02/07 15:13:06'), which is a format the Date constructor can comprehend.
U can subtract like this--
var d1 = new Date(); //"now"
var d2 = new Date("2011/02/01") // some date
var diff = Math.abs(d1-d2); // difference in milliseconds
var days = diff*24*60*60*1000;
You code is actually subtracting March 1 from April 1, as the months in JavaScript dates are 0-based.
var sysdt = "02/28/2013";
var date1 = new Date(sysdt);
var userdt = "03/01/2013"
var date2 = new Date(userdt);
var days = (date2-date1)/(1000*24*60*60);
or subtract 1 from month in your code
var sysdt = "02/28/2013";
var year = sysdt.substring(6,10);
var mon = sysdt.substring(0,2)-1; // months are from 0 to 11
var date = sysdt.substring(3,5);
var n = Date.UTC(year,mon,date);
var userdt = "03/01/2013"
var yr = userdt.substring(6,10);
var mn = userdt.substring(0,2)-1; // months are from 0 to 11
var dd = userdt.substring(3,5);
var n1 = Date.UTC(yr,mn,dd);
var days = (n1-n)/(1000*24*60*60);

Count Number of days between 2 dates in javascript

Please help me get the number of days between today's date and some other date.. Here is my example
It gives me NaN
Here is what I came up with. My demo
var cellvalue="2011-08-18 11:49:01.0 IST";
var firstDate = new Date();
var secondDate = cellvalue.substring(0, cellvalue.length-4);
alert(diffOf2Dates(firstDate,secondDate));
function diffOf2Dates(todaysDate,configDate)
{
/*var udate="2011-08-18 11:49:01.0";
var configDate=new Date(udate);*/
var oneDay = 24*60*60*1000; // hours*minutes*seconds*milliseconds
var firstDate = todaysDate; // Todays date
var secondDate = new Date(configDate);
var diffDays = Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay));
console.info(firstDate+", "+secondDate);
//console.info(Math.ceil(diffDays));
return Math.ceil(diffDays);
}
Use
var firstDate = new Date(); // Todays date
var secondDate = new Date(2011,08,19, 11,49,01);
var diffDays = (firstDate.getDate() - secondDate.getDate());
It was showing NAN as your constructor is wrong. check yourself by alerting secondDate in your original code
Edit : above code will work if both dates are in same month, for general case
var oneDay = 24*60*60*1000;
var diffDays = Math.abs((firstDate.getTime() - secondDate.getTime()) / oneDay);
Also this will give result as fraction of date, so if you want to count whole dates you can use Math.ceil or Math.floor
Use this:
var udate="2011-08-19 11:49:01.0 GMT+0530";
The IST part is not valid
your input date is incorrect that is why it is failing. anyways here is some code that should help you with it.
var DateDiff = {
inDays: function(d1, d2) {
var t2 = d2.getTime();
var t1 = d1.getTime();
return parseInt((t2-t1)/(24*3600*1000));
},
inWeeks: function(d1, d2) {
var t2 = d2.getTime();
var t1 = d1.getTime();
return parseInt((t2-t1)/(24*3600*1000*7));
},
inMonths: function(d1, d2) {
var d1Y = d1.getFullYear();
var d2Y = d2.getFullYear();
var d1M = d1.getMonth();
var d2M = d2.getMonth();
return (d2M+12*d2Y)-(d1M+12*d1Y);
},
inYears: function(d1, d2) {
return d2.getFullYear()-d1.getFullYear();
}
}
var udate="2011-08-05 11:49:01";
var configDate=new Date(udate);
var oneDay = 24*60*60*1000; // hours*minutes*seconds*milliseconds
var firstDate = new Date(); // Todays date
var secondDate = new Date(udate);
alert(secondDate);
var diffDays = DateDiff .inDays(firstDate,secondDate);
alert(diffDays );
if you have udate format like 28-07-2011 you can use this
var checkindatestr = "28-07-2011";
var dateParts = checkindatestr.split("-");
var checkindate = new Date(dateParts[2], dateParts[1] - 1, dateParts[0]);
var now = new Date();
var difference = now - checkindate;
var days = difference / (1000*60*60*24);
alert(days);
how to compare two dates in jquery
You are calculating the difference correctly but the problem is that secondDate is an invalid date. Date cannot work with that date format, it needs "August 08, 2011 11:49:01" as input - and if your date has a different format then you have to convert it. Note that Date has only rudimentary timezone recognition, you can only be sure that "UTC" or "GMT" will be recognized correctly - you shouldn't use other time zones.
The problem is with your udate variable value. The date format is not correct. Try initializing the date in this format:
var secondDate = new Date(year,month,date);

Categories

Resources