Prepending text to html elements using a Javascript function - javascript

I'm trying to use Javascript for formatting the time to a localized format using Intl.DateTimeFormat method.
I have several instances of time strings in 24h format i want to localize in a HTML page, for example:
<span class="timeclass">18:45</span> //and so on..
And i am able to format the time with the following code, which uses a Date object:
let locale = 'en-US'; // this variable changes, example 'en-UK', etc
let time = new Date('1971-12-12T18:45');
console.log(new Intl.DateTimeFormat(locale, {
hour: 'numeric',
minute: 'numeric',
}).format(time)); //output is "6:45 PM"
As the code shows, i added a dummy date in order for the Date object to be semantically correct. Now, i'm trying to write a function to replace all instances of times contained within timeelem classes:
var locale = 'en-US';
var timeformat = new Intl.DateTimeFormat(locale, {
hour: 'numeric',
minute: 'numeric',
});
timeelements = document.querySelectorAll('.timeclass');
timeelements.forEach((element) => {
timeelements.textContent= timeformat.format(timeelements.textContent);
});
But it is not working because it is getting the time in the format 18:45 instead of 1971-12-12T18:45. What is the best way to prepend such dummy date to the string? The date is only relevant for the localization function to work, by the way.

You can choose any date you want, as long as it is in the correct format. You can do something like this: WORKING DEMO
HTML
<span class="timeclass">18:45</span>
<span class="timeclass">18:15</span>
<span class="timeclass">11:45</span>
<span class="timeclass">02:45</span>
<span class="timeclass">22:45</span>
<span class="timeclass">23:45</span>
<span class="timeclass">18:00</span>
JAVASCRIPT
timeelements = document.querySelectorAll('.timeclass');
timeelements.forEach((element) => {
console.log("elem ", element.innerHTML);
// Append any date. Use your birthday.
const timeString12hr = new Date('1970-01-01T' + element.innerHTML + 'Z')
.toLocaleTimeString({}, {
timeZone: 'UTC',
hour12: true,
hour: 'numeric',
minute: 'numeric'
});
element.innerHTML = timeString12hr
});
------------------------UPDATED------------------------
var locale = "en-US";
var timeformat = new Intl.DateTimeFormat(locale, {
hour: 'numeric',
minute: 'numeric',
});
timeelements = document.querySelectorAll('.timeclass');
timeelements.forEach((element) => {
console.log("elem ", element.innerHTML);
const timeString12hr = new Date('1970-01-01T' + element.innerHTML + 'Z');
element.innerHTML = timeformat.format(timeString12hr)
});

Related

HTML JavaScript to add Date format not working correctly

I put the my html code to Australia/Sydney Date format,
but its not working correctly, it always shown currant date, like as Friday, December 9, 2022 dose any one know the solution?
Australia date now Saturday, December 10, 2022
Thank you
here is my code
const datesausDiv = document.getElementById('date-div-aus');
function myDateFunction() {
const now = new Date();
const timeZones = ['Australia/Sydney'];
const options = {
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric'
};
const nowStr = now.toLocaleString('en-US', options);
datesausDiv.innerHTML = nowStr;
}
setInterval(myDateFunction, 1000);
<div id="date-div-aus"> </div>
The wording of the question is pretty confusing, but it sounds like you're trying to display the current date in Australia to users who are not necessarily in Australia.
You defined a "timezone" array but didn't do anything with it; it needs to be fed in as one of the options:
const datesausDiv = document.getElementById('date-div-aus');
function myDateFunction() {
const now = new Date();
const options = {
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric',
timeZone: "Australia/Sydney"
};
const nowStr = now.toLocaleString('en-US', options);
datesausDiv.innerHTML = nowStr;
}
setInterval(myDateFunction, 1000);
<div id="date-div-aus"> </div>
(Note: to the likely resigned chagrin of the residents of Perth, the above pretends that Australia has only one timezone.)
The following demonstrates how you can present the same (current) time in different formats and for different global locations:
const now = new Date();
console.log("Sydney:",now.toLocaleString('en-GB', {timeZone:"Australia/Sydney"}));
console.log("New York:",now.toLocaleString('en-US', {timeZone:"America/New_York"}));
console.log("here:",now.toLocaleString());
<div id="date-div-aus"> </div>
Based on this wiki, it says that "Australians typically write the date with the day leading, as in the United Kingdom and New Zealand".
This means that dates have these possible formats:
4 December 2022
2022-12-04 or 04/12/2022
Therefore, the only fix you need is to use en-GB.
Please let me know if this is what you were searching for, else provide an example of the format you wish the date to show up. Have a nice day.
const datesausDiv = document.getElementById('date-div-aus');
function myDateFunction() {
const now = new Date();
const options = {
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric'
};
const nowStr = now.toLocaleString('en-GB', options);
datesausDiv.innerHTML = nowStr;
}
setInterval(myDateFunction, 1000);
<div id="date-div-aus"> </div>
Split the string on each forward slash to get the day, month and year. Pass the year, month minus 1 and the day to the Date() constructor. The Date() constructor creates and returns a new Date object.

Convert an input type time, to a timestamp for firestore

Convert an input type time, to a timestamp for firestore
<input type="time" class="form-control job-field" id="starttime" name="starttimeadd" placeholder="Job Start Time" required>
This is what I have tried but no luck, I did have a couple of results trying a different method but that showed an invalid date or NaN.
var starttimestamp = moment.utc(moment("#starttimeadd")).format();
This is the expected result
This is my code
function addJob(){
var starttimeadd = $('#starttimeadd').val();
const starttimestamp = moment.utc(moment(starttimeadd)).format();
db.collection("jobs").doc().set({
starttime: starttimestamp,
})
.then(function() {
console.log("Document successfully written!");
})
.catch(function(error) {
console.error("Error writing document: ", error);
});
}
moment takes a date as a parameter, not an element ID like you're trying to do here. How about:
const startTimeAdd = document.getElementById("starttimeadd").value;
const starttimestamp = moment.utc(startTimeAdd).format();
Also worth considering that you may not need to use Moment for this - the official docs recommend reading an article on why you may not need Moment
Close enough. Using Intl.DateTimeFormat (no momentjs)
//code assumes that you have validated the input
var startTime = "01:00"; // document.querySelector("#starttime").value;
var formattedStartDateFromTime = getFormattedDateFromTime(startTime);
console.log(formattedStartDateFromTime);
function getFormattedDateFromTime(time) {
var timeParts = time.split(":");
var startDate = new Date();
startDate.setHours(+timeParts[0]);
startDate.setMinutes(+timeParts[1]);
startDate.setSeconds(0);
var options = {
year: 'numeric',
month: 'long',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
timeZoneName: 'short'
};
return new Intl.DateTimeFormat('en', options).format(startDate);
}
Browser compatibility: Chrome, Edge, Firefox, IE11+

Convert Timestamp to a Value for different Timezones in Javascript

I have different timestamps and a timezones coming from an API as an object. Example:
{{'ts' : 1521311400000},
{'tz' : 'GMT+01:00'}}
How can I convert the timestamp to a human readable Date in that timezone using toLocaleTimeString()? I have tried to pass the timezone inside the options object as the value for timeZone as stated here but I get an invalid time zone in DateTimeFormat() Error and cant figure out how the correct Format should be.
To get that kind of flexibility in formatting dates, you'll probably want to look into Moment and Moment Timezone.
If you'd like another option, you could try this:
function init() {
function formatFixedTimeZone(ts, tz) {
let offsetStr = tz.replace(/:/g, '');
let reverseOffset = offsetStr.replace(/[-+]/, sign => sign === '+' ? '-' : '+');
let time = new Date(ts);
let timeStr = time.toUTCString().replace('GMT', reverseOffset);
time = new Date(Date.parse(timeStr));
timeStr = time.toLocaleString('en-US', {
timeZone: 'UTC', // Don't change this from UTC for other time zones.
weekday: 'short',
month: 'short',
day: 'numeric',
year: 'numeric',
hour: '2-digit',
minute: '2-digit',
second: '2-digit'
}) + ' ' + tz;
return timeStr;
}
let timeDisplay = document.getElementById('time');
function tick() {
let nowStr = formatFixedTimeZone(Date.now(), 'GMT+01:00');
timeDisplay.textContent = nowStr;
}
setInterval(tick, 1000);
}
Plunker here: http://plnkr.co/edit/Gk6SOLwpWqfoT5gHlCrb?p=preview
This displays a running count of the current time in a fixed time zone, but I've tried to write it in such a way that if you aren't using the current time, but the ts and tz values from your API, it shouldn't be too hard to adapt this to your needs and to different output formatting.

How to convert "2016-02-23T11:31:36.23" into JavaScript object?

I am trying to convert string from the following format into JavaScript Date() object. Then I want to change the format into mm/dd/yyyy h:MM AM/PM using the jquery-dateFormat UI
2016-02-23T11:31:36.23
I tried to do this
function formatDateTime(str) {
var dt = new Date(str);
return $.format.date(dt, "mm/dd/yyyy h:MM TT");
}
But this is giving me this 00/NaN/NaN NaN:NaN TT
How can I correctly convert the string into a date object?
According to the documentation I should be able to convert isoDateTime into an object just like I have done
You can parse de string into a new date and use toLocaleDateString (plain js):
var strdate = "2016-02-23T11:31:36.23";
var date = new Date(Date.parse(strdate));
var options = { year: 'numeric', month: 'numeric', day: 'numeric', hour: 'numeric', minute: 'numeric' };
console.log(date.toLocaleDateString('en-US', options));
Fiddle on: https://jsfiddle.net/fcLkrwv6/

Convert Date of Birth to Javascript Date

I have a standard date in ISO format: 1950-01-01 (date of birth)
And I need to convert it to a javascript object, so I can convert it to US Format (01/01/1050).
However when I convert it, it changes it to: Sat Dec 31 1949 17:00:00 GMT-0700
I just need it converted, without any offsets, or changes. If they were born on x day, it is x day.
Here is what I am doing currently:
$("#dob1").val( new Date(client.dob1).toLocaleDateString('en', { day: '2-digit', month: '2-digit', year: 'numeric' }) )
client.dob1 = "1950-01-01"
Final working result, in case anyone stumbles upon this:
$("#dob1").val( new Date(client.dob1).toLocaleDateString('en', { day: '2-digit', month: '2-digit', year: 'numeric', timeZone: "UTC" }) )
You can also replace the dashes with slashes, and make a new Date() from the resulting string.
(some code from https://stackoverflow.com/a/29185654/2033574)
// Manually
date1 = new Date("1950/01/01")
// Or programmatically:
dashDate = "1950-01-01"
date2 = new Date(dashDate.replace(/-/g, '/'))
// Same output
document.write(date1 + "<br>" + date2)
You can simple create a Date object like this.
new Date('2015-10-13')
You can read here more about Date

Categories