Modify values of date/time text string in HTML with JS/jQuery

Viewed 204

I’d like to convert part of a date/time text string to a number, perform addition/subtraction on it, taking into account the am/pm switch-over at 12:00, and run it behind the original. Possible?

For example, in the existing HTML,

<span class="time">12:30pm EST</span>

should display as

<span class="time">12:30pm EST / 9:30am PST</span>
2 Answers

You can use moment js library for this. Inside this library, you can pass your current time and convert it to the preferred timezone. Please check the example below:

time = document.getElementsByClassName("time")[0]
var estTime = moment(time.innerHTML, "h:mm A");


var pstTime = estTime.clone().tz("America/Los_Angeles").format("h:mm a")

time.innerHTML = time.innerHTML + " / "+pstTime + " PST"
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.7/moment-timezone-with-data-2010-2020.min.js"></script>

<span class="time">12:30pm EST</span>

Yes you can do that. Check this example below.

I'm using new ECMAScript features like const, array destructuring but if can also use var and access the array data using the traditional way (array[0] and array[1])

$(document).ready(function(){
  $('#button').click(function(){
    // Get the time text
    const time = $('.time').text();
    
    // Split the string in two parts
    const [firstPart, secondPart] = time.split(':');
    
    const hours = Number(firstPart);
    
    // Get only the minutes and discard the rest 
    const minutes = Number(secondPart.substring(0, 2));
    
    // Hours and minutes are numbers, so you can perform addition
    $('#result').text(`${hours + 5}:${minutes}`);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="time">12:30pm EST</div>

<button id="button">Transform</button>

<div id="result"></div>

Related