1

I have this input <input type="datetime-local" id="myTime" /> in my HTML code. I am using javascript to take the value of this input var myTime = document.getElementById("myTime").value; but I need to add one hour to the value and save it in another variable. The format of the datetime is "yyyy-mm-dd HH:MM:SS".

I know it seems very easy but I have tried many ways and I just can't get it right. I would appreciate a little help with this one.

Thanks!

mauguerra
  • 3,728
  • 5
  • 31
  • 37
  • You are actually asking 3 questions: how to parse a timestamp to a Date, how to add an hour, then how to format a string to save elsewhere. Hence the 3 duplicates. There are many questions and answers on each of those topics already. – RobG Apr 09 '20 at 08:52

4 Answers4

3

You can do get value from myTime control, then convert it into a new Date object, then simply add 1 hour to it.

(Click on the button in demo to get the updated date)

var myTime = document.getElementById("myTime");
myTime.value = new Date().toISOString().slice(0,16);

function getDatetime() {
  var str = myTime.value;    
  var d = new Date(str);
  console.log('Before:\t', d.toLocaleString())
  
  // Add 1 hour to datetime
  d.setHours(d.getHours() + 1);
  
  console.log('After:\t', d.toLocaleString())
}
<input type="datetime-local" id="myTime" />
<button onclick="getDatetime()">Click me</button>
palaѕн
  • 72,112
  • 17
  • 116
  • 136
1

d = new Date('2020-04-09 10:10:00'); // Converted to UTC Time Zone
console.log(d);
d.setHours(d.getHours() + 1);
console.log(d);

d1 = new Date('2020-04-09 10:10:00'+'+0500'); // Desired Time Zone added.
console.log(d1);
d1.setHours(d1.getHours() + 1);
console.log(d1);

console.log(d.toLocaleString("en-US", {timeZone: "Australia/Brisbane"}), d.toLocaleString("en-US", {timeZone: "Asia/Shanghai"}), d.toLocaleString("en-US", {timeZone: "Asia/Karachi"})) // Displayed as Time Zone's Date settings.

console.log(d1.toLocaleString("en-US", {timeZone: "Australia/Brisbane"}), d1.toLocaleString("en-US", {timeZone: "Asia/Shanghai"}), d1.toLocaleString("en-US", {timeZone: "Asia/Karachi"})) // Displayed as Time Zone's Date settings.
Umair Khan
  • 1,684
  • 18
  • 34
1

you can do this way, try this

$( document ).ready(function() {

DateObj = Date.parse("10/20/2017 16:00");

// vale you get $("#myTime").val(value);

var date = new Date(DateObj+3600000);

    console.log(date.toLocaleString('en-US',{ hour12: false }));
});
Narendra Chouhan
  • 2,291
  • 1
  • 15
  • 24
1
   for `<input type="datetime-local" id="myTime" />` input field in html put below code in you document ready function or on Change function to get one hour ahead of input time.                                                                  

var today = new Date(document.getElementById("myTime").value);
today.setHours(today.getHours() + 1);
console.log(today)
Shohanur
  • 116
  • 7