Convert utc time into local time of specifc format - javascript

I have a date string of format dd.MM.yyyy HH:mm:ss but its UTC which I want to convert to local. How can I do it using moment library?
const dateStr = '20.09.2018 16:12:37';
const format = 'dd.MM.yyyy HH:mm:ss';
// for local time of UTC +3.00 new date Str will be 20.09.2018 19:12:37

You have to use moment.utc(String, String) to parse your string using UTC mode
By default, moment parses and displays in local time.
If you want to parse or display a moment in UTC, you can use moment.utc() instead of moment()
Then you can use local() to convert it to local time:
Sets a flag on the original moment to use local time to display a moment instead of the original moment's time.
Please note that since you input dateStr is not in ISO 8601/RCF 2822 recognized format you have to specify format when parsing it. Morover moment tokens are case sensitive so you have to use uppercase YYYY instead of yyyy to parse years and uppercase DD to parse day of the month since lowercase dd stands for day of the week (Mon, Tue, etc).
Here a live sample:
const dateStr = '20.09.2018 16:12:37';
const format = 'DD.MM.YYYY HH:mm:ss';
console.log(moment.utc(dateStr, format).local().format(format));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.min.js"></script>
Have a look at Local vs UTC vs Offset guide to better understand how UTC and locale mode work in momentjs.

To convert from UTC to Local you need to use moment.local() method
const dateStr = '20.09.2018 16:12:37';
const format = 'DD.MM.YYYY HH:mm:ss';
var newDate = moment.utc().format(format);
var temp= moment.utc(newDate, format);
var local = moment(temp).local().format(format);
More info on the official Documentation

Related

date-fns/format always takes local timezone

From below code:
const dateString = '1994-09-15T12:00:00-03:00';
const parsedDate = parseISO(dateString)
const dateFormat = 'MM-dd-yyyy HH:mm:ss xxx'
console.log(format(parsedDate, dateFormat, { }))
I expect:
09-15-1994 20:30:00 -03:00 But i get 09-15-1994 20:30:00 +05:30 as my local timezone is +05:30
What am i missing here?
The parseDate() creates a date based on GMT, e.g. is adjusted by 3h based on your input '1994-09-15T12:00:00-03:00'.
The format() function with xxx formats local time without the Z, such as -08:00, +05:30, +00:00. If you want to format with GMT string, specify OOOO, which will give you something like GMT-08:00, GMT+05:30, or GMT+00:00, which again has the offset adjusted based on your browser's time zone.
See Time-Zones docs below if you want to format to a time zone other than your browser's one, such as GMT-03:00.
Docs:
ISO 8601: https://en.wikipedia.org/wiki/ISO_8601
parseDate(): https://date-fns.org/v2.29.2/docs/parseISO
format(): https://date-fns.org/v2.29.2/docs/format
Time-Zones: https://date-fns.org/v2.29.2/docs/Time-Zones

Set CET timezone with toISOString()

How do I change the MYSQL timestamp date to the JS date using toISOString () and setting the time-zone to CET?
This is what I use and it returns the following format "2021-02-251 15:27:20" which is what I want, only the time should be +1 hour "2021-02-251 16:27:20 ":
registration_date_customer.toISOString().replace(/T/, ' ').replace(/\..+/, '')
The time on the database is correct (16:27:20).
Does anyone know how to set the CET time-zone?
You can use Date.localeString() to format in the correct timeZone, the IANA timezone "Europe/Paris" is equivalent to CET. Using the "sv" locale will result in an ISO formatted string (Sweden uses ISO date formatting).
const registration_date_customer = new Date("2021-02-25 15:27:20Z");
console.log(registration_date_customer.toLocaleString("sv", { timeZone: "Europe/Paris"}));

Convert a German date to ISO date

I am developing a Node.js application and I have to convert a German string date like am 13. Dezember 2017 to ISO Date and when I used moment.js library to convert it I got an invalid date, any solutions?
You can parse 13. Dezember 2017 using moment(String, String, String) and then use toISOString().
Since your input is neither in ISO 8601 recognized format, neither in RFC 2822 you have to provide format parameter. DD stands for day of the month, MMMM stands for month's name and YYYY stands for 4 digit year.
The third parameter tells moment to parse input using given locale:
As of version 2.0.0, a locale key can be passed as the third parameter to moment() and moment.utc().
Note that you have to import de locale to make it work (using moment-with-locales.js or /locales/de.js in browser or following Loading locales in NodeJS section for node).
Here a live example:
var m = moment('13. Dezember 2017', 'DD MMMM YYYY', 'de');
console.log( m.toISOString() );
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment-with-locales.min.js"></script>
You can use the toISOString method, it return a Date object as a String, using the ISO standard:
var d = new Date();
var n = d.toISOString();
Have a look here:
https://momentjs.com/docs/
Do you need something like that:
moment('13. Dezember 2017', 'DD. MMMM YYYY', 'de').format(moment.ISO_8601);
You can easily format it using:
var now = moment(); // pass your date to moment
var formatedNow = moment().toISOString(now);
or
var formatedNow = now.toISOString();

momentjs unix timestamp converts pm to am

I am having a problem with Moment.js.
Here are the codes.
var date = "2016-07-26 06:15 pm";
var unixDate = moment(date).unix();
var renderDate = moment.unix(unixDate).format("YYYY-MM-DD hh:mm a");
console.log(renderDate);
I want the value of "renderDate" to be same as the value of "date" variable. However, what gets printed out in the console is "2016-07-26 06:15 am".
I am completely lost as to why everything remains the same except "am/pm" at the end.
unix method accepts only number
You need to parse date before usage
moment('2016-07-28 06:15 PM', 'YYYY-MM-DD hh:mm a').format('YYYY/MM/DD hh:mm a')
Look at http://momentjs.com/docs/. You can only use the string without a format if it is in ISO 8601 format. In your example, it ignored the am/pm indicator and viewed the hour as being in 24-hour format.

Convert (YYYY/MM/DD HH:MM:SS.MS) GMT to local time using JavaScript

For some reason, the SOAP response from one of my WebService looks like this:
2010/07/08 04:21:24.477
Where the date format is YYYY/MM/DD and the time is GMT.
I'm not really sure how to convert this to local time because the format is so odd.
Date.parse should actually parse most of the date string into its respective timestamp.
The 2 caveats appear to be:
Milliseconds aren't supported, so they have to be separated and added after parsing.
It'll assume local time, so 'GMT' or 'UTC' should to be appended before parsing.
With these in mind, the following should work:
function parseSoapDate(dateString) {
var dateParts = dateString.split('.'),
dateParse = dateParts[0],
dateMilli = dateParts[1];
return new Date(
Date.parse(dateParse + ' GMT') +
parseInt(dateMilli, 10)
);
}
var date = parseSoapDate('2010/07/08 04:21:24.477');
As for UTC to local time, JavaScript's Date objects should already handle that for you as they can report the date in both UTC and the user's local timezone. You specify which you want by the name of the method (whether it has UTC in it or not):
alert(date.toString()); // local time
alert(date.toUTCString()); // UTC time
This should work:
var dateStr = "2010/07/08 04:21:24.477";
var d = new Date(dateStr.split('.')[0]);
d.setUTCHours(0);
my JSON returns: YYYY-MM-DD HH:MM:SS, localization will work only on selected browsers Date.prototype.toLocaleDataString("en-us"[,option] )
function stringToDate(s) {
var language = window.navigator.userLanguage || window.navigator.language;
var options = {year: "numeric", month: "numeric", day: "numeric"};
s = s.split(/[-: ]/);
d = new Date(Date.UTC(s[0], s[1]-1, s[2], s[3], s[4], s[5]));
return d.toLocaleDateString( language , options)+" "+d.toLocaleTimeString();
}
// return
// Friday, November 15, 2013 2:21:04 PM --> FF25
// 11/15/2013 2:21:04 PM --> Chrome31
It looks like the response of the date/time is in ISO format, which is a sensible way to provide date information.
Suppose that the date returned is 7-8-2010. Would this be the 8th of July or the 7th of August? Having the date in ISO format (YYYY/MM/DD) solves this ambiguity.
You can convert this date to the required format in many different ways, i.e.
var input = '2010/07/08 04:21:24.477';
var now = new Date(input.slice(0, input.indexOf('.')));
alert(now.toLocaleString());
You may want to search the Internet for the Date object or to find snippets which will allow you to convert a date using many different formats.

Categories