Search This Blog

Tuesday, July 25

Snippet for change Date and Time Based on Hours

<!DOCTYPE html>
<html>
<body>

<p>Click the button to display a date after changing it to 48 hours ago.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>
<p id="demo1"></p>

<script>
function myFunction() {
    var d = new Date();
    d.setHours(d.getHours() + 48);
  
    var date_time = JSON.parse(formatAMPM(d))
  
    document.getElementById("demo").innerHTML = date_time['Date'];
    document.getElementById("demo1").innerHTML = date_time['Time'];

}


function formatAMPM(date) {
 
  var dd = date.getDate();
  var mm = date.getMonth()+1; //January is 0!
  var yyyy = date.getFullYear();
 
  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 obj = new Object();
   obj.Date = mm + '/' + dd + '/' + yyyy;
   obj.Time  = hours + ':' + minutes + ' ' + ampm;
   var jsonString= JSON.stringify(obj);
     
  //var strTime = mm + '/' + dd + '/' + yyyy +'  ' + hours + ':' + minutes + ' ' + ampm;
  return jsonString;
}

</script>

</body>
</html>

No comments:

Post a Comment