toLocaleString adding custom letters - javascript

In this code below I need to render time looking like this 3h15m. Now it's just 3:15. How can I add endings to hours and minutes? Thank you in advance.
<span className={s.data}>{new Date(ticket.segments[0].duration)
.toLocaleString('en', { hour: 'numeric',
minute: 'numeric' })}</span>

Like this
let [, hh, mm] = new Date(2020, 07, 12, 15, 30, 0)
.toLocaleString('en', {
hour: 'numeric',
minute: 'numeric'
}).match(/(\d{1,2})\:(\d{2})/)
console.log(`${hh}h${mm}m`)

Related

get new Date() in other timezone in full text string format

I need to get Thailand timezone in this format: Thu Nov 10 2022 14:08:37 GMT+0800 (Malaysia Time). I have tried new Date().toLocaleString("en-US", {timeZone: "Asia/Bangkok"}) but didn't get the correct format I want, probably because of the .toLocaleString(). Is there a simple way to do it?
As deceze suggests, you can use Intl.DateTimeFormat with suitable options to get the values you want. Then you can use formatToParts to reorganise them as you wish, e.g. to replicate the format of Date.prototype.toString for any timezone, you can use:
// Return timestamp in same format as Date.prototype.toString
// in designated timezone (IANA representative location)
function toTimezone(tz, date = new Date()) {
// Get parts except timezone name
let opts = {
year: 'numeric',
month: 'short',
day: '2-digit',
weekday: 'short',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
timeZone: tz,
timeZoneName: 'shortOffset',
hour12: false
}
// To get full timezone name
let opts2 = {
hour: 'numeric',
timeZone: tz,
timeZoneName: 'long'
}
let toParts = opts => new Intl.DateTimeFormat('en', opts)
.formatToParts(date)
.reduce((acc, part) => {
acc[part.type] = part.value;
return acc;
}, Object.create(null));
let {year, month, day, weekday, hour, minute,
second, timeZoneName} = toParts(opts);
// Fix offset
let sign = /\+/.test(timeZoneName)? '+' : '-';
let [oH, oM] = timeZoneName.substr(4).split(':');
let offset = `GMT${sign}${oH.padStart(2, '0')}${oM || '00'}`;
// Get timezone name
timeZoneName = toParts(opts2).timeZoneName;
return `${weekday} ${month} ${day} ${year} ${hour}:${minute}:${second} ${offset} (${timeZoneName})`;
}
// Examples
['Australia/Adelaide',
'Asia/Bangkok',
'Asia/Kolkata',
'America/New_York',
'Pacific/Yap',
'Pacific/Pago_Pago'
].forEach(tz => console.log(toTimezone(tz)));
Support for some options like shortOffset may not be ubiquitous yet. A formatting library with timezone support is a simpler (and more reliable) option. :-)
You can configure the locale string formatter with a whole bunch of options:
console.log(new Date().toLocaleString('en-US', {
timeZone: 'Asia/Bangkok',
weekday: 'short',
year: 'numeric',
month: 'short',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
timeZoneName: 'short',
hour12: false
}));
However, the exact format it will output will always be dependent on the locale used and the browser's understanding of how dates should be formatted for that locale. If you want more control over the exact formatting, you'll need to cobble it together yourself:
const date = new Date();
const time = date.toLocaleString('en-US', {
timeZone: 'Asia/Bangkok',
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
timeZoneName: 'short',
hour12: false
});
const weekday = date.toLocaleString('en-US', {
timeZone: 'Asia/Bangkok',
weekday: 'short'
});
console.log(`${weekday} ${date.getFullYear()} ... ${time}`);
If that seems too complicated, use some 3rd party library like Luxon, which can simplify that a bit.

Date.toLocaleString inadequacy for conversion of a date/time to universal time

I'm trying to convert a date object to UTC. Either I'm using it wrong or the Date.toLocaleString seems to be broken or inadequate.
new Date('Tue Aug 09 2022 18:43:00 GMT-0500 (Central Daylight Time)')
.toLocaleString('en-US', {
timeZone: "UTC",
day: "2-digit",
hour12: false,
year: "numeric",
month: "2-digit",
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
})
output:
"08/09/2022, 23:43:00" (A valid date/time)
new Date('Tue Aug 09 2022 19:43:00 GMT-0500 (Central Daylight Time)')
.toLocaleString('en-US', {
timeZone: "UTC",
day: "2-digit",
hour12: false,
year: "numeric",
month: "2-digit",
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
})
output:
"08/10/2022, 24:43:00"
I expected it to be "08/10/2022, 00:43:00" but instead it appears to not reset the hours.
I have worked around this, in the particular way I was using the result, but I would like to be able to go without the extra conditional and reset.
var parts = str.match(/(\d{2})\/(\d{2})\/(\d{4}),\s(\d{2})\:(\d{2})\:(\d{2})/),
month = parseInt(parts[1], 10),
day = parseInt(parts[2], 10),
year = parseInt(parts[3], 10),
hours = parseInt(parts[4], 10),
minutes = parseInt(parts[5], 10),
seconds = parseInt(parts[6], 10);
if (hours == 24) {
hours = 0;
}
Why is this happening, and how can I accomplish my goal?
Use hourCycle: "h23" instead of hour12: false in your options. Read more about the options on MDN.
console.log(
new Date('Tue Aug 09 2022 19:43:00 GMT-0500 (Central Daylight Time)')
.toLocaleString('en-US', {
timeZone: "UTC",
day: "2-digit",
hourCycle: "h23",
year: "numeric",
month: "2-digit",
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
})
);
.as-console-wrapper { max-height: 100% !important; height: 100%; }
I suppose it's the americain way of displaying time after midnight when using 24-hour (non 12 hour) time. Try using en-UK for locale:
console.log(
new Date('Tue Aug 09 2022 19:43:00 GMT-0500 (Central Daylight Time)')
.toLocaleString('en-UK', {
timeZone: "UTC",
day: "2-digit",
hour12: false,
year: "numeric",
month: "2-digit",
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
})
);

convert or change dates format

I am facing an issue in javascript dates, i want to change minutes
my react component
//real time date
var currDate = new Date();
var dd = new Date().setMinutes(currDate.getMinutes() - 30); //reduce 30 minutes
var ddPLus = new Date().setMinutes(currDate.getMinutes() + 30); //add 30 minutes
var ddPLusHour = new Date().setMinutes(currDate.getMinutes() + 60); //add 30 minutes
var reductedTime = new Date(dd);
var addedTime = new Date(ddPLus);
var addedHour = new Date(ddPLusHour);
console.log({ // this.setState({
current: new Date().toLocaleTimeString(),
slotTime: reductedTime.toLocaleTimeString([], {
hour: '2-digit',
minute: '2-digit'
}),
slotTime1: new Date().toLocaleTimeString([], {
hour: '2-digit',
minute: '2-digit'
}),
slotTime2: addedTime.toLocaleTimeString([], {
hour: '2-digit',
minute: '2-digit'
}),
slotTime3: addedHour.toLocaleTimeString([], {
hour: '2-digit',
minute: '2-digit'
})
})
my output
04:00 PM
04:46 PM
05:16 PM
05:46 PM
Expected output
04:00 PM
04:30 PM
05:00 PM
05:30 PM
what should i do? anyone help me?
Your code is hard to understand.
You could consider using Luxon
Did you mean
const aMinute = 60000;
var currDate = new Date()
currDate.setHours(16,0,0,0,0); // remove when tested
const reductedTime = new Date(currDate.getTime() - (30*aMinute)); // reduce 30 minutes
const addedTime = new Date(currDate.getTime() + (30*aMinute)); // add 30 minutes
const addedHour = new Date(currDate.getTime() + (60*aMinute)); // add 1 hour
console.log({ // this.setState({
current: currDate.toLocaleTimeString(),
slotTime: reductedTime.toLocaleTimeString([], {
hour: '2-digit',
minute: '2-digit'
}),
slotTime1: new Date().toLocaleTimeString([], { // why this? Same as currDate
hour: '2-digit',
minute: '2-digit'
}),
slotTime2: addedTime.toLocaleTimeString([], {
hour: '2-digit',
minute: '2-digit'
}),
slotTime3: addedHour.toLocaleTimeString([], {
hour: '2-digit',
minute: '2-digit'
})
})
I would recommend to use moment.js library for any kind of Dates format change and calculation. it has many builtin useful method.
e.g.
const date = moment(new Date(), "hh:mm:ss A")
.add(seconds, 'seconds')
.add(minutes, 'minutes')
.format('LTS');

Date time in Arabic JavaScrript

I have a problem in JavaScript function
var tDate = new Intl.DateTimeFormat("ar-US", {
day: 'numeric',
month: 'long',
year: 'numeric'
}).format(Date.now()) +
'\xa0\xa0/ \xa0' +
new Intl.DateTimeFormat("ar-FR-u-ca-islamic", {
day: 'numeric',
month: 'long',
year: 'numeric'
}).format(Date.now());
console.log(tDate);
the output in Arabic is :
4 أبريل 2020 / 11 شعبان 1441 هـ
in English :
April 5, 2020 / Shaʻban 12, 1441 AH
what is the problem in Arabic , number 4 moved to left why??
The output of date formatting using the Intl object is not necessarily consistent across implementations. For me, the OP code produces different results in different browsers:
Safari: ٦ أبريل، ٢٠٢٠ / ١٣ شعبان، ١٤٤١
Firefox: ٦ أبريل ٢٠٢٠ / ١٣ شعبان ١٤٤١ هـ
Chrome: 6 أبريل 2020 / 13 شعبان 1441 هـ
None of them are exactly the same in format or characters.
If you want to ensure the components are in the order you want, use formatToParts, collect the parts then output them in the order you want. Just ensure the result is unambiguous (e.g. use the month name as you've done).
let partsHeg = new Intl.DateTimeFormat('ar-FR-u-ca-islamic', {
day: 'numeric',
month: 'long',
year: 'numeric'
}).formatToParts(Date.now());
partsHeg.forEach(part => {
if (part.type != 'literal') {
console.log(part.type + ': ' + part.value);
}
});
let partsGre = new Intl.DateTimeFormat('ar-US', {
day: 'numeric',
month: 'long',
year: 'numeric'
}).formatToParts(Date.now());
partsGre.forEach(part => {
if (part.type != 'literal') {
console.log(part.type + ': ' + part.value);
}
});
You can fix this by adding a one (1) statement/code of the RTL Unicode to fix the direction. This happens when the last or first letter in an Arabic text is a Latin char.
let RTL = "\u200F"; // Added ****
var tDate = RTL + new Intl.DateTimeFormat("ar-US", { // Added RTL before
day: 'numeric',
month: 'long',
year: 'numeric'
}).format(Date.now()) +
'\xa0\xa0/ \xa0' +
new Intl.DateTimeFormat("ar-FR-u-ca-islamic", {
day: 'numeric',
month: 'long',
year: 'numeric'
}).format(Date.now());
console.log(tDate); // You can add RTL here instead console.log(RTL+tDate);

date.toLocaleString(options) does not work javascript

I am quite new to JS and need some help.
I want to format date with the help of toLocaleString(). According to standards first argument 'locales' can be omitted. My code looks like:
let myDate = new Date(2014, 0, 30)
let options = {
year: '2-digit',
month: '2-digit',
day: '2-digit'
};
let formattedDate = myDate.toLocaleString(options);
console.log(formattedDate);
While you can skip the first argument, without supplying something for it in your case, you won't get the options argument to give you the results you want.
Here are a few versions of working code:
let date = new Date(2014, 0, 30);
let options = {
year: '2-digit',
month: '2-digit',
day: '2-digit'
};
console.log(date.toLocaleString('en-us', options));
console.log(date.toLocaleString(undefined, options));
console.log(date.toLocaleString(options));
options.timeZone = 'UTC';
options.timeZoneName = 'short';
console.log(date.toLocaleString('en-US', options));
// sometimes even the US needs 24-hour time
console.log(date.toLocaleString('en-US', { hour12: false }));
The first argument to toLocaleString is not optional, but you can pass undefined to it.
let date = new Date(2014, 0, 30)
let options = {
year: '2-digit',
month: '2-digit',
day: '2-digit'
};
let formattedDate = date.toLocaleString(undefined, options);
console.log(formattedDate);
You should use the options as second parameter:
let date = new Date(2014, 2, 2)
let options = {
year: '2-digit',
month: '2-digit',
day: '2-digit'
};
let formattedDate = date.toLocaleString(undefined, options);

Categories

Resources