convert string date and time to utc based on timezone using moment - javascript

am using moment in nodejs server to convert local time from frontend to utc.
my time format is date = '10-07-2020 08:45 PM' in string format. When i use moment(date).format() its converting format to this 2020-10-07 20:45:00+05:30 timezone is adding based on server and i have timezone = '+4:00' this is my local timezone. I would like to convert my date string to UTC based on the timezone field not based on the server timezone. How can I do this?
I tried the following methods but am not getting a proper solution
moment.utc(moment(date).utcOffset(timezone)).format('YYYY-MM-DD HH:mm:ss')
Anyone Please suggest

You can use moment-timezone to create a date from a string and a certain timezone. In order to do that you need to specify your format and the corresponding timezone. Something like this:
const date = moment.tz("10-07-2020 08:45 pm", "M-D-YYYY hh:mm a", "Europe/Samara");
console.log(date.toISOString());
<script src="https://momentjs.com/downloads/moment.min.js"></script>
<script src="https://momentjs.com/downloads/moment-timezone-with-data.min.js"></script>

Instead of moment, perhaps use intl DateTimeFormat?
Here are some possibilities
const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric', hour: 'numeric', minute: 'numeric', second: 'numeric', };
const date = new Date('10-07-2020 08:45 PM')
console.log(date)
options.timeZone = 'Europe/Ulyanovsk';
options.timeZoneName = 'short';
console.log(new Intl.DateTimeFormat('en-US', options).format(date));

Related

Get milliseconds for custom date in custom timezone

I have a date server api that works in Europe/Moscow timezone. The selected date must be sent from the client as a timestamp for the Europe/Moscow timezone.
A client from Canada choosing a date in the calendar, say November 8, 2011 has to send the timestamp in the Europe/Moscow timezone.
I can solve this problem through moment.js, but unfortunately, for certain reasons I can't use third-party libraries in the project.
Basically I need a function that does the same thing as the moment.tz method:
moment.tz('2021-11-08T00:00:00', 'Europe/Moscow');
You can use Intl.DateTimeFormat with suitable options to get a timestamp for any IANA location. The formatToParts method gets the required values, then it's just a matter of formatting them. E.g.
function toLocTimestamp(loc, date = new Date()) {
let {year, month, day, hour, minute, second, timeZoneName} = new Intl.DateTimeFormat('en', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
hour12: false,
timeZone: loc,
timeZoneName: 'short'
}).formatToParts().reduce((parts, part) => {
parts[part.type] = part.value;
return parts;
}, Object.create(null));
// Check if timezone not offset and fix
if (!/\d/.test(timeZoneName)) {
timeZoneName = date.toLocaleString('fr',{
hour: 'numeric',
timeZone: loc,
timeZoneName: 'short'
}).match(/\S+$/)[0];
}
// Change timeZoneName to offset
let sign = timeZoneName.substring(3,4);
let offset = timeZoneName.substring(4);
let [offH, offM] = offset.split(':');
// Return timestamp
return `${year}-${month}-${day}T${hour}:${minute}:${second}${sign}${offH.padStart(2,'0')}:${offM || '00'}`;
}
// E.g.
['Europe/Moscow', 'Asia/Kolkata','Australia/Lord_Howe',
'America/St_Johns'].forEach(
loc => console.log(`${loc.padEnd(20,' ')}: ${toLocTimestamp(loc)}`)
);
The timeZoneName fix is required as depending on the language passed to dateTimeFormat and host system language, the offset might be GMT±H[:mm], UTC±H[:mm] or an abbreviation like "ChST" or "CET". If en returns an abbreviation, fr shouldn't.
This will observe DST for various locations. If a fixed offset is required, just adjust the UTC time by the offset, use toISOString to get the timestamp and remove the trailing Z.

redefine Date() javascript

The official calendar of our country is jalali!
Jalali is a type of calendar that has a mathematical relationship with the Gregorian calendar.
I want to change Date() in JS to returns jalali values.
there are many lib or func for this, but I don't want use them.
Can I redefine Date()?
Where can I view Date() source?
You can use toLocaleDateString();
let today = new Date().toLocaleDateString('fa-IR');
console.log(today);
fa-IR is for Farsi-Iran, but all the ISO country codes can be found here
also you can set options as second argument, for example:
let options = { year: 'numeric', month: 'long', day: 'numeric' };
new Date().toLocaleDateString('fa-IR', options);
Don't mess with objects you don't own. You can create your own date object called maybe jDate (after "jalali date", which I assume is the same as the Intl object's "persian" calendar) and implement methods there.
The Intl.DateTimeFormat constructor returns an object that has a formatToParts method that you can leverage to implement the Date methods you need, then you can work on a standard Date object underneath but return Jalali values from the methods. e.g. to get all the current date parts in English:
let f = new Intl.DateTimeFormat('en-GB-u-ca-persian',{
year: 'numeric',
month: 'long',
day: 'numeric',
weekday: 'long',
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
hour12: false,
});
console.log('Current Jalali date: ' + f.format(new Date()));
console.log('The parts:');
f.formatToParts(new Date()).forEach(part => console.log(part.type + ': ' + part.value));
For some things you have to run the format method more than once with different options, e.g. to get both the month name and number as both are specified by the month option: month: 'long' for the name and month: 'numeric' for the number.

How to format the date to (dd/mm/yyyy hh:mm:ss)

How can I convert the date below into this template (dd/mm/yyyy hh:mm:ss) ?
05/04/2021 14:52
I tried to do it that way, but I only get the time and not the date with time.
var data = new Date('05/04/2021 14:52');
var time = data.toLocaleTimeString('pt-PT', {hour12: false});
console.log(time);
You can use below script
var data = new Date('05/04/2021 14:52');
console.log(data.toLocaleString('en-GB',{hour12: false}));
Output : "04/05/2021, 14:52:00"
If you need more date-related staff than simple date formatting, you can use Moment.js.
moment().format('MMMM Do yyyy, h:mm:ss a'); // April 5th 2021, 9:16:13 pm
moment().format('DD/MM/yyyy hh:mm'); // 05/04/2021 21:18
If you need to format your date object, simply use:
moment(date).format('DD/MM/yyyy hh:mm');
Moment.js is also useful for operation on dates like days, week, month adding/subtracting, getting the start of a week, month, quarter, and many other useful operations.
This is my solution. If you want to create a advanced format, you can read more about object Intl
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl
const formatDate = new Intl.DateTimeFormat("en" , {
day: "2-digit",
month: "2-digit",
year: "numeric",
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
hour12: false
});
console.log(formatDate.format(new Date('05/04/2021 14:52')))

JavaScript - Moment and Date.toLocaleDateString keeps returning my time when using a different locale

I started off using the Moment library to try to get the time for Germany using the following code:
import moment from 'moment'
import 'moment/locale/de'
moment.locale('de');
console.log(moment().format('LTS'));
However, it kept returning my time, British summer time (BST)
I figured maybe it was an issue with the library, so I rewrote it without using the library like so:
const options = { hour: 'numeric', minute: 'numeric', second: 'numeric' }
const test = new Date();
console.log(test.toLocaleDateString('de-DE', options));
Yet this also returns my time... (with the added date, month and year as expected)
Am I doing something wrong? Or maybe it's something to do with how Chrome outputs to the console?
Moment locale refers to language not timezone.
You'll need moment timezone for that:
moment().tz('CET').format('LTS')
EDIT
As suggested by RobG, could also be achieved without moment:
new Date().toLocaleString('de-DE', { timeZone: 'Europe/Berlin' });
document.getElementById('date').innerHTML = new Date().toLocaleString('de-DE', { timeZone: 'Europe/Berlin' });
<div id="date"/>
With toLocaleString you can use the timeZone option, however it may not be supported everywhere you need it to be:
var options = {hour: 'numeric', minute: 'numeric', second: 'numeric', timeZone: 'Europe/Berlin'};
var test = new Date();
console.log(test.toLocaleDateString('de-DE', options));
Here's how you can do it using moment -
function toTimeZone(time, zone) {
var format = 'YYYY/MM/DD HH:mm:ss ZZ';
return moment(time, format).tz(zone).format(format);
}
console.log(toTimeZone(new Date(), "UTC"));
<script src="http://momentjs.com/downloads/moment.min.js"></script>

Javascript date objects always one day behind [duplicate]

This question already has answers here:
Wrong Date in Javascript
(3 answers)
Closed 6 years ago.
I am trying to convert a date object from the backend db to a string to present on the view, however, when I convert it, the result is always one day behind.
The code:
date = this.props.date;
d = new Date(date)
options = {
month: "long", weekday: "long", year: "numeric",
day: "numeric"
};
dateStr = d.toLocaleDateString("en-us",options)
EDIT examples provided:
Regarding backend structure, the date is inserted into the database via a simple html datepicker form.
Currently, this.props.date, if rendered on the view, will render something like this:
"2016-10-01"
When I use the code above, it would become:
"Friday, September 30, 2016"
Assuming your backend date is in UTC specifically ISO8601 and you want the displayed date to be UTC in en-us language-region.
var date = "2016-10-01";
var parts = date.split('-');
parts[1] -= 1;
var d = new Date(Date.UTC.apply(null, parts));
options = {
month: "long",
weekday: "long",
year: "numeric",
day: "numeric",
timeZone: 'UTC'
};
document.getElementById('out').textContent = d.toLocaleDateString("en-us", options);
<pre id="out"></pre>
Assuming the date is UTC and the Date object handles ISO8601 correctly (some older versions do not) then you could rely on the built in parsing of Date.
var date = "2016-10-01";
var d = new Date(date);
options = {
month: "long",
weekday: "long",
year: "numeric",
day: "numeric",
timeZone: 'UTC'
};
document.getElementById('out').textContent = d.toLocaleDateString("en-us", options);
<pre id="out"></pre>
So all I have done is explicitly set the output to be UTC, otherwise it is using your runtime's default time zone. Worth noting that toLocaleDateString is still in its infancy and can vary across browsers, just like ISO8601 parsing.

Categories

Resources