This question already has answers here:
Calculate age given the birth date in the format YYYYMMDD
(45 answers)
Closed 7 years ago.
I want to calculate age of anything.i already wrote the program. I took a date object and assigned value into it $birth_date=new Date('Dec,15,1992'); then i subtract the value with the current data.According to the subtraction it should returns 23 years 0 months 14 days.but it returns 23 years 4 months 14 days.years and days are OK but the month misleads.
would you pls tell me why showing this weird results?
following code is HTML and next to Javascript
$(document).ready(function(){
var birth_date = new Date('Dec, 15, 1992').getTime();
var years,months,days, hours, minutes, seconds;
var ageCount = document.getElementById('counter');
setInterval(function(){
var current_date = new Date().getTime();
var total_sec =(current_date-birth_date) / 1000;
years=parseInt(total_sec/(86400*30*12));
var second_left=total_sec%(86400*30*12);
months=parseInt(second_left/(86400*30));
second_left=second_left%(86400*30);
days=parseInt(second_left/86400);
second_left=second_left%(86400);
hours=parseInt(second_left/3600);
second_left=second_left%3600;
minutes=parseInt(second_left/60);
seconds=parseInt(second_left%60);
ageCount.innerHTML=years+' Years '+months+' Months '+days+' Days '+hours+
' Hours '+minutes+' Minutes '+seconds+' Seconds';
},500);
});
<div id="counter">
</div>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
I think it would make more sense to just use the basic notations as listed here for getting metrics such as date , hour , minutes, seconds from the date difference
$(document).ready(function(){
var birth_date = new Date('Feb, 15, 1992');
var years,months,days, hours, minutes, seconds;
var ageCount = document.getElementById('counter');
setInterval(function(){
var current_date = new Date();
var YearDiff = (current_date.getYear() - birth_date.getYear());
var monthDiff = (current_date.getMonth() - birth_date.getMonth());
var daysDiff = (current_date.getDate() - birth_date.getDate());
var hoursDiff = (current_date.getHours() - birth_date.getHours());
var minDiff = (current_date.getMinutes() - birth_date.getMinutes());
var secDiff = (current_date.getSeconds() - birth_date.getSeconds());
ageCount.innerHTML=YearDiff+' Years '+monthDiff+' Months '+daysDiff+' Days '+hoursDiff+
' Hours '+minDiff+' Minutes '+secDiff+' Seconds';
},500);
});
https://jsfiddle.net/DinoMyte/138bhovx/2/
You Can simply make this calculation with the following implementation.
https://jsfiddle.net/wqm704xm/1/
var birthday = new Date('Dec,15,1992');
var today;
var $dateEl = document.getElementById('date');
setInterval(writeValue, 100);
function writeValue() {
today = new Date();
var calculatedDate = calculate(normalizeDate(birthday), normalizeDate(today));
$dateEl.innerHTML =
'years: ' + calculatedDate.year + '<br>' +
'months: ' + calculatedDate.month + '<br>' +
'days: ' + calculatedDate.day + '<br>' +
'hours: ' + calculatedDate.hours + '<br>' +
'minutes: ' + calculatedDate.minutes + '<br>' +
'seconds: ' + calculatedDate.seconds + '<br>'
;
}
function calculate(firstDate, currentDate) {
return {
year: currentDate.year - firstDate.year,
month: currentDate.month - firstDate.month,
day: currentDate.day - firstDate.day,
hours: currentDate.hours - firstDate.hours,
minutes: currentDate.minutes - firstDate.minutes,
seconds: currentDate.seconds - firstDate.seconds
}
}
function normalizeDate(date) {
return {
year: date.getFullYear(),
month: date.getMonth() + 1,
day: date.getDate(),
hours: date.getHours(),
minutes: date.getMinutes(),
seconds: date.getSeconds()
};
}
<div id="date"></div>
Months is incorrect because you are assuming that every month is only 30 days long, when months can be 28, 29, 30 or 31 days in length (and in some circumstances, other lengths).
To quickly see where you are going wrong, and ignoring leap years, 30/days a month would mean 30*12 only 360 days per year. That means every year you miss 5 days. So given 23 years, that's roughly 23*5 days difference, or ~4 months.
There were 5 leap years in between your date and now, adding 5 more days to the difference. This completely accounts for your 4 months (120 days).
You need to adjust your algorithm to account for these differences.
Additional info:
If you are using this in production code and require accurate dates - please keep in mind a date is not sufficient information to calculate precise differences in terms of number of days. You'll also need information such as time zone and location and handle all sorts of lovely time discontinuations.
For example: In 2011 Samoa jumped to the other side of the international date line. So 29-Dec-2011 to 1-Jan-2012 is 1 day longer in Australia than it was in Samoa.
(╯°□°)╯︵ ┻━┻
Related
I have this code which generates the current date + time in javascript:
var date_variable = new Date();
var year = date_variable.getFullYear();
var month = date_variable.getMonth() + 1;
var day = date_variable.getDate();
var hour = date_variable.getHours();
var minutes = date_variable.getMinutes();
var seconds = date_variable.getSeconds();
var full_date = year + month + day + hour + minutes + seconds;
console.log(year);
console.log(month);
console.log(day);
console.log(hour);
console.log(minutes);
console.log(seconds);
console.log(full_date);
Everything in console displays fine, except when it comes to the full_date variable. This is what's displayed in console:
2014
8
27
10
53
10
2122
My question is, why does the last output not combine my date + time into a single string?
Thanks
You need to concatenate the numbers with a string first.
var full_date = year +""+ month +""+ day +""+ hour +""+ minutes +""+ seconds;
Each of the properties you are accessing return a number. When you add them together with the + operator, you are just adding numbers together.
If you substitute the variables used in full date, it would look something like:
var full_date = 2014 + 8 + 26 + . . .
All you have to do is put a strings in the expression and you will get what you want.
In all honesty though, you should use Date.toLocalDateString() or Date.toLocalTimeString() if the format works for you. You can read the documentation about them on MDN's Date reference page.
This question already has answers here:
Formatting the date time with Javascript
(12 answers)
Closed 8 years ago.
I need to change a date/time from 2014-08-20 15:30:00 to look like 08/20/2014 3:30 pm
Can this be done using javascript's Date object?
Yes, you can use the native javascript Date() object and its methods.
For instance you can create a function like:
function formatDate(date) {
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0'+minutes : minutes;
var strTime = hours + ':' + minutes + ' ' + ampm;
return (date.getMonth()+1) + "/" + date.getDate() + "/" + date.getFullYear() + " " + strTime;
}
var d = new Date();
var e = formatDate(d);
alert(e);
And display also the am / pm and the correct time.
Remember to use getFullYear() method and not getYear() because it has been deprecated.
DEMO http://jsfiddle.net/a_incarnati/kqo10jLb/4/
Please do not reinvent the wheel. There are many open-source and COTS solutions that already exist to solve this problem.
Please take a look at the following JavaScript libraries:
Luxon: [CDN] | [Source] | [Minified]
Moment.js: [CDN] | [Source] | [Minified]
Datejs: [CDN] | [Source] | [Alpha1.zip (1.6MB)]
Demo
Update: I wrote a one-liner using Moment.js Luxon below.
const { DateTime } = luxon;
const value = DateTime
.fromFormat("2014-08-20 15:30:00", "yyyy-MM-dd HH:mm:ss")
.toFormat('MM/dd/yyyy h:mm a');
console.log(value); // 08/20/2014 3:30 PM
<script src="https://cdnjs.cloudflare.com/ajax/libs/luxon/1.26.0/luxon.min.js"></script>
Here is the original version using Moment. Since Luxon is the successor to Moment, I have included this as an alternative.
const value = moment('2014-08-20 15:30:00').format('MM/DD/YYYY h:mm a');
console.log(value); // 08/20/2014 3:30 pm
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
For the date part:(month is 0-indexed while days are 1-indexed)
var date = new Date('2014-8-20');
console.log((date.getMonth()+1) + '/' + date.getDate() + '/' + date.getFullYear());
for the time you'll want to create a function to test different situations and convert.
I don't think that can be done RELIABLY with built in methods on the native Date object. The toLocaleString method gets close, but if I am remembering correctly, it won't work correctly in IE < 10. If you are able to use a library for this task, MomentJS is a really amazing library; and it makes working with dates and times easy. Otherwise, I think you will have to write a basic function to give you the format that you are after.
function formatDate(date) {
var year = date.getFullYear(),
month = date.getMonth() + 1, // months are zero indexed
day = date.getDate(),
hour = date.getHours(),
minute = date.getMinutes(),
second = date.getSeconds(),
hourFormatted = hour % 12 || 12, // hour returned in 24 hour format
minuteFormatted = minute < 10 ? "0" + minute : minute,
morning = hour < 12 ? "am" : "pm";
return month + "/" + day + "/" + year + " " + hourFormatted + ":" +
minuteFormatted + morning;
}
You can do that:
function formatAMPM(date) { // This is to display 12 hour format like you asked
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0'+minutes : minutes;
var strTime = hours + ':' + minutes + ' ' + ampm;
return strTime;
}
var myDate = new Date();
var displayDate = myDate.getMonth()+ '/' +myDate.getDate()+ '/' +myDate.getFullYear()+ ' ' +formatAMPM(myDate);
console.log(displayDate);
Fiddle
I'm using a mysql timestamp to calculate the difference of time through JavaScript as below,
function parseMySQLTimestamp(timestamp) {
var parts = timestamp.match(/^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})$/);
return new Date(+parts[1], (+parts[2] - 1), +parts[3], +parts[4], +parts[5], +parts[6]);
}
var informTime = "2011-11-09 08:00:00";
var diff = (new Date()- parseMySQLTimestamp(informTime));
var months = Math.floor(diff /(60*60*24*30*1000));
diff=Math.abs(diff-(months*60*60*24*30*1000));
var days = Math.floor(diff/(60 * 60 * 24*1000));
diff=Math.abs(diff-(days*60*60*24*1000));
var hour=Math.floor(diff/(60*60*1000));
diff=Math.abs(diff-(hour*60*60*1000));
var minute=Math.floor(diff/(60*1000));
var message=months +" months "+ days + " D " + hour + " Hr " + minute + "min ago ";
alert(message);
it will give the correct result but I'm afraid that it will not be correct in the months which have 31,28 or 29 days other wise in leap years.
How to achieve reliable functionality? I feel it's so complicated. Thank you.
I'm trying to calculate remaining time (ex: 10 years, 2 months and 10 days from today(2014/03/02) in JS using this function:
var d2 = new Date(2024, 3, 12);
var d1 = new Date();
var d0 = new Date(1970, 0, 1);
var diff = new Date(d2.getTime() - (d1.getTime() + d0.getTime() ) );
var years = diff.getFullYear();
var months = diff.getMonth();
var days = diff.getDay();
alert("remaining time = " + years + " years, " + months + " months, " + days + " days.");
But instead of get the 10 years difference, I got 1980 years difference (though the days difference I understand that are produced buy the variation of days in months and years):
Is it possible to perform this "remaining time" operation using this strategy? If so, how to get the expected result?
Here the function in a JS shell: jsfiddle.net/3ra6c/
I find here the solution I was looking for:
var date1 = new Date();
var date2 = new Date(2015, 2, 2);
var diff = new Date(date2.getTime() - date1.getTime());
var years = diff.getUTCFullYear() - 1970; // Gives difference as year
var months = diff.getUTCMonth(); // Gives month count of difference
var days = diff.getUTCDate()-1; // Gives day count of difference
alert("remaining time = " + years + " years, " + months + " months, " + days + " days.");
And it seems to work very well!
As I explained, Date is not equipped with such functions and you have to do the math yourself. You can get the milliseconds difference between two dates, but then it's down to doing the math to represent that as you wish.
An example of using moment.js, loaded with require.js, with humanized approximations.
Javascript
require.config({
paths: {
moment: 'http://momentjs.com/downloads/moment.min'
}
});
require(['moment'], function (moment) {
var x = moment(new Date(2024, 3, 12)).from(new Date());
console.log(x);
});
Output
in 10 years
On jsFiddle
Look at their docs to see how you can humanize the output, you may want a little more detail.
var diff = new Date(d2.getTime() - (d1.getTime() + d0.getTime() ) )
Why do you add d0? Try to remove it.
Hi I have the following problem I am converting this UNIX timestamp to javascript string for date: here is the jsfiddle for it http://jsfiddle.net/tczeU/ and as everyone can see the date is 2 6 2013 13:15:44 so the problem is that this number 1373969744 in UNIX timestamp converter is Tue, 16 Jul 2013 10:15:44 GMT The problem are that there are 14 days bwtween the two dates where does I go wrong? Please help me to convert this date. The code is as in the fiddle:
var date = new Date(1373969744*1000);
var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();
var year = date.getFullYear();
var day = date.getDay();
var month = date.getMonth();
var string =day + " " + month + " " + year + " " + hours + ':' + minutes + ':' + seconds;
$("#view").html(string);
and the html:
<div id="view"></div>
So no errors there. Please help. Any help will be apreciated!
You are using the wrong function to get the day of the month. You are using the function that returns the day of the week, hence the 2 since it's a Tuesday. Check out http://www.w3schools.com/jsref/jsref_obj_date.asp
You need to change .getDay to .getDate and it will work just fine. Or at least it did for me using your jsFiddle link.
Also, don't forget to add one to your month so it has Jul as 7th month instead of 6th like you have it now.