I'm obtaining data.value which is a time in the format: hh:mm a - for example 12:30 am.
I also know:
the local timezone of the user (userTimeZone)
the timezone of the venue (venueTimeZone)
I need to convert the time selected by the user (data.value) to the correct date in the venueTimeZone. For example, if the user is in Americas/New York and they selected 1:30PM on the 20/05/2022, and the venue is in Americas/Los Angeles - the value I am interested in obtaining is 20/05/2022 10:30AM.
This is my attempt, however the timezone itself doesn't change - I think this is because when I create the userDateTime with moment I don't specify a time offset, but I'm not sure how to obtain the offset from userTimeZone, whilst accounting for DST.
const userTimeZone = _.get(
Intl.DateTimeFormat().resolvedOptions(),
['timeZone']
);
const venueDateStr = new Date().toLocaleString('en-US', {
timeZone: venueTimeZone,
});
const Date = new Date(restaurantDateStr);
const venueYear = venueDate.getFullYear();
const venueMonth = `0${venueDate.getMonth() + 1}`.slice(-2);
const venueDateOfMonth = `0${venueDate.getDate()}`.slice(-2);
const userDateTime = createDateAsUTC(
moment(
`${venueDateOfMonth}/${venueMonth}/${venueYear} ${data.value}`,
'DD/MM/YYYY hh:mm a'
).toDate()
).toLocaleString('en-US', { timeZone: venueTimeZone });
EDIT - I do not have the city offset, I have the timezone name, therefore I cannot use any suggested answer which relies on city offset.
Consider using Luxon - the successor to Moment. (See Moment's project status.)
// Parse your input string using the user's local time zone
// (this assumes the current local date)
const local = luxon.DateTime.fromFormat('1:30 pm', 'h:mm a');
// Convert to the desired time zone
const converted = local.setZone('America/Los_Angeles');
// Format the output as desired
const formatted = converted.toFormat('dd/MM/yyyy h:mm a').toLowerCase();
console.log(formatted);
<script src="https://cdnjs.cloudflare.com/ajax/libs/luxon/2.4.0/luxon.min.js"></script>
You could also do this without a library, however you may find that not all browsers will parse the input string, and your output format is up to the browser as well.
// Get the current local date as a string
const date = new Date().toLocaleDateString();
// Parse the date and time in the local time zone
// Warning: This is non-standard and may fail in some environments
const dt = new Date(date + ' 1:30 pm');
// Format the output, converting to the desired time zone
const result = dt.toLocaleString(undefined, { timeZone: 'America/Los_Angeles' });
console.log(result);
There are, of course, manual ways to parse and format dates (using regex, etc.) but I'll leave that up to you or another person to complete.
Related
in a project we are using momentjs with date. And from backend we become the date in the following format: 2016-10-19T08:00:00Z (don't ask me why...)
Now we are setting a new date in frontend from some selectboxes. And I am trying to convert this in the same format:
const date = '25.03.2021';
const hour = '13';
const minute = '45'; // this 3 values come from value of selectboxes
const rawDate = moment(date).hour(hour).minute(minute);
// trying to convert to 2021-03-25T13:45:00Z
rawDate.format(); // output: 2021-03-25T13:45:00+00:00
rawDate.format('DD.MM.YYYY hh:mm:ss'); // output: 03.01.2022 08:00:00
rawDate.format('DD.MM.YYYY hh:mm:ss z'); // output: 03.01.2022 08:00:00 UTC
rawDate.format('DD.MM.YYYY hh:mm:ss Z'); // output: 03.01.2022 08:00:00 +00:00
rawDate.toISOString(); // output: 2022-01-03T08:00:00.000Z
I know I could probably just use format() or toISOString() and slice/replace the last bit. But I like to know is there a way without any string concat/manipulation?
You could use moment.utc() to ensure your date is in UTC, then use .format() with the format string DD-MM-YYYYTHH:mm:ss[Z].
I'd also suggest explicity defining the format you are parsing from in the moment() call, e.g. pass 'DD.MM.YYYY' as the second argument.
The reason the backend takes dates in this format is that it's a standardized way of formatting dates to make them machine-readable and consistent (ISO 8601)
const date = '25.03.2021';
const hour = '13';
const minute = '45';
// Raw date will be in the UTC timezone.
const rawDate = moment(date, 'DD.MM.YYYY').hour(hour).minute(minute).utc();
console.log(rawDate.format('DD-MM-YYYYTHH:mm:ss[Z]'));
<script src="https://momentjs.com/downloads/moment.js"></script>
You can try convert to UTC ..?
i.e. Do you intend to make use of a UTC date/time..?
const date = '2021-03-25';
const hour = '13';
const minute = '45'; // this 3 values come from value of selectboxes
const rawDate = moment(date).hour(hour).minute(minute);
const utc = moment.utc(rawDate);
console.log(rawDate.format('DD.MM.YYYY hh:mm:ss'));
console.log(utc.format()); //2021-03-25T11:45:00Z
I'm trying to do this without adding moment js to my project but it seems more difficult than I'd like.
if I get a date that's formatted as : "2021-07-19T12:15:00-07:00"
Is there an efficient way to have it formatted as:
"12:15 pm"
regardless of where me and my browser are located?
I've gotten as far as some other answers with no luck, for example:
var date = new Date('2021-07-19T12:15:00-07:00')
var userTimezoneOffset = date.getTimezoneOffset() * 60000;
new Date(date.getTime() - userTimezoneOffset);
Thanks!
You could use Date.toLocaleTimeString() to format the time, this will give you the time in the local timezone, if we remove the UTC offset.
There are other options available here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat
let timestampWithUTCOffset = "2021-07-19T12:15:00-07:00";
let timestampWithoutUTCOffset = timestampWithUTCOffset.substr(0,19);
console.log( { timestampWithUTCOffset , timestampWithoutUTCOffset });
let dt = new Date(timestampWithoutUTCOffset);
console.log('Time of day:', dt.toLocaleTimeString('en-US', { timeStyle: 'short' }))
I'm trying to convert the time ( time alone ) from a known timezone to my local timezone with Moment.js.
I wrote the following function and, I am getting invalidDate as the output.
const convertToLocalTime = (time, tz) => {
const t = moment.tz(time, tz)
const localTime = t.local()
}
time is just time; without any date eg: 10:06 am and,
tz is a timezone string for eg: Europe/Berlin
What am I doing wrong?
See Parsing in Zone:
The moment.tz constructor takes all the same arguments as the moment constructor, but uses the last argument as a time zone identifier.
Since your input (10:06 am) is not in ISO 8601/RFC 2822 recognized format (see moment(String) docs), you have to pass format parameter as shown in moment(String, String).
Here a live sample:
const convertToLocalTime = (time, tz) => {
const t = moment.tz(time, 'hh:mm a', tz)
const localTime = t.local()
return localTime;
}
const res = convertToLocalTime("10:06 am", 'Europe/Berlin');
console.log( res.format('hh:mm a') );
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.14/moment-timezone-with-data-2012-2022.min.js"></script>
I have a list of list of string dates like this: '17/12/2017 19:34'. They are CET dates.
How can I transform it to the user's browser date?
I'm doing this:
const tzGuess = moment.tz.guess()
export const toTimeZone = (time) => {
const format = 'DD/MM/YYYY HH:mm'
return moment(time, format).tz(tzGuess).format(format)
}
console.log(toTimeZone('17/12/2017 19:34', tzGuess))
but how can I say to moment that the date I'm passing at first is a CET one?
Thanks!
You can use moment.tz function for parsing time string using a given timezone (e.g. 'Europe/Madrid').
The issue is: what do you mean with CET? If your input has fixed UTC+1 offset (like Central European Time), then you can use RobG's solution. If you have to consider both CET and CEST, I think that the best soution is to use moment.tz.
Here a live code sample:
const tzGuess = moment.tz.guess()
const toTimeZone = (time) => {
const format = 'DD/MM/YYYY HH:mm'
return moment.tz(time, format, 'Europe/Madrid').tz(tzGuess).format(format)
}
console.log(toTimeZone('17/12/2017 19:34', tzGuess))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.4/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.13/moment-timezone-with-data-2012-2022.min.js"></script>
A great resource about timezone is the timezone tag info page.
Without moment.js, parse the string to a Date, treating it as UTC, then adjust for the CET offset (+0100). You can then format it using local time values for the client:
// Parse date in format DD/MM/YYYY HH:mm
// Adjust for CET timezone
function parseCET(s) {
var b = s.split(/\D/);
// Subtract 1 from month and hour
var d = new Date(Date.UTC(b[2], b[1]-1, b[0], b[3]-1, b[4]));
return d;
}
var s = '17/12/2017 19:34';
console.log(parseCET(s).toString());
However, if the time needs to observe daylight saving (CEST) for the source time stamp, you'll need to account for that.
I have two variables in javascript like:
time: 02:00
date: 25-08-2017
and I'm wondering if I can put these into a Date() object and get the UTC date and time out of it in hours/minutes using getUTCDay(), getUTCHours() and getUTCMinutes() and place them back in the format I got them.
I can load moment.js for it but if I don't have to it would be nice if I can do it without.
Convert your strings to an ISO 8601 string and use it in the Date constructor. From there, you can get whatever data you need
let time = '02:00'
let date = '25-08-2017'
let iso8601Date = date.split('-').reverse().join('-')
let dt = new Date(`${iso8601Date}T${time}`) // will be interpreted as local time
const digitFormatter = new Intl.NumberFormat(undefined, {minimumIntegerDigits: 2})
console.info('Parsed date:', dt)
console.info('UTC date in dd-mm-yyyy:',
`${digitFormatter.format(dt.getUTCDate())}-${(digitFormatter.format(dt.getUTCMonth() + 1))}-${dt.getUTCFullYear()}`
)
console.info('UTC time:', `${digitFormatter.format(dt.getUTCHours())}:${digitFormatter.format(dt.getUTCMinutes())}`)