Click here to Skip to main content
15,888,733 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i want to add hour and minit to current time.for example right now time is 2:00 PM if i give input 20:00 it will change not only the time at the same time date is also be changed.how can i accomplish this?

What I have tried:

i have tried many ways but couldnot do that
Posted

The title is clearer than your question. So I will answer to the title.
First thing first, the relevant references on JavaScript DateTime are here:
1. JavaScript Dates[^]
2 .JavaScript Date Formats[^]
3. JavaScript Date Methods[^]
Do go through them after my explanation and example code shown below.
First, convert any date time components into milliseconds, including the interval;
Second, perform any desired arithmetic calculation using the milliseconds;
Lastly, convert the resulting milliseconds back to the new date time.
Study the example code which is adequately commented:
<!DOCTYPE html>
<html>
<body>

<p id="startDateTime"></p>
<p id="futureDateTime"></p>

<script>
var startDateTime = new Date(2017,0,2,12,30,00,0);
document.getElementById("startDateTime").innerHTML = startDateTime;

// convert the startDate into milliseconds
var startDateTimeInMilliseconds = startDateTime.getTime();

// what is the date time 12 hours 30 minutes away?
// change the 12 hours to milliseconds
var hoursInMilliseconds = 12*60*60*1000;	// milliseconds
// likewise, change the 30 minutes to milliseconds
var minutesInMilliseconds = 30*60*1000;   // milliseconds

// the future date in milliseconds is
var futureInMilliseconds = startDateTimeInMilliseconds + hoursInMilliseconds + minutesInMilliseconds;

// convert milliseconds to date time
var futureDateTime = new Date(futureInMilliseconds);

document.getElementById("futureDateTime").innerHTML = futureDateTime;
</script>

</body>
</html>
A demo version at JSFiddle[^]
Cross-referencing with the above links to better understand my code.
 
Share this answer
 
v2
Comments
Rakib Ahmed 2-Jan-17 6:57am    
Thanks :D
Peter Leow 2-Jan-17 7:46am    
You are welcome.
If you want to add a time period to a date, you basically have to convert both of them into milliseconds.

Here is a link to solve your problem.

Add two dates times together in javascript - Stack Overflow[^]
 
Share this answer
 
Quote:
i have tried many ways but could not do that
There is mainly 1 single way.
Search about DateTime datatype and study associated functions.
Goolgle is your friend.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900