Thanks for looking.
So I've been working on this script for a few hours today and I can't work out why the "currentDate" variable is only applying to the first item in the loop. Basically, I would like both items to update.
When this script loads the date string is taken from each list item and then populated to convert the date and time based on Timezone.
Any help appreciated.
const date = {
month: "short",
day: "numeric"
};
const time = {
hour: '2-digit',
minute: "numeric",
hour12: true,
timeZoneName: "short"
};
var children = $(".test-list");
for (var i = 0; i < children.length; i ) {
var currentItem = children.eq(i);
var currentDate = currentItem.children().eq(i).find(".cms-date-time").text();
let timeFormat = new Date(currentDate ' GMT 1'.replace(/-/g, "/"))
currentItem.children().eq(i).find('.date').html(Intl.DateTimeFormat(navigator.language, date).format(timeFormat));
currentItem.children().eq(i).find('.time').html(Intl.DateTimeFormat(navigator.language, time).format(timeFormat));
console.log(timeFormat);
}
CodePudding user response:
Perhaps because you are iterating .test-list
when you mean to be iterating .test-list .test-item
. A simpler and more jQuery-ish way of going about it might be
const date = {
month: "short",
day: "numeric"
};
const time = {
hour: '2-digit',
minute: "numeric",
hour12: true,
timeZoneName: "short"
};
$(".test-list .test-item").each(function(i, o) {
let currentDate = $(o).find(".cms-date-time").text();
let timeFormat = new Date(currentDate ' GMT 1'.replace(/-/g, "/"))
$(o).find('.date').html(Intl.DateTimeFormat(navigator.language, date).format(timeFormat));
$(o).find('.time').html(Intl.DateTimeFormat(navigator.language, time).format(timeFormat));
//console.log(timeFormat);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
<div role="list" >
<div role="listitem" >
<h1 >Marscast</h1>
<h1 >October 5, 2022 10:00 PM</h1>
<div >
<div>Converted Date:</div>
<h1 >Oct 5</h1>
</div>
<div>
<div>Converted Time:</div>
<h1 >02:00 PM PDT</h1>
</div>
</div>
<div role="listitem" >
<h1 >Bingo Night</h1>
<h1 >October 6, 2022 9:00 PM</h1>
<div >
<div>Converted Date:</div>
<h1 >Heading</h1>
</div>
<div>
<div>Converted Time:</div>
<h1 >Heading</h1>
</div>
</div>
</div>
</div>