I have problem showing timezone with moment.js.
I tried with this code:
var result = moment(someDate).format("MM/DD/YYYY HH:mm A Z");
and I get return, for example: 08/05/2015 06:18 PM +02:00, which is fine, but I want that my output be like 08/05/2015 06:18 PM WEDT or something like that, with abbreviations of timezones.
Tried using this code, but I get empty timezone on the end:
var result = moment(someDate).format("MM/DD/YYYY HH:mm A z");
or
var result = moment(someDate).format("MM/DD/YYYY HH:mm A zz");
UPDATE
So as #Matt Johnson suggested, I used this approach to show time zone using moment-timezone-with-data.js and tzdetect.js:
var tzName = tzdetect.matches()[0];
var result = moment.tz(myDate, tzName).format("MM/DD/YYYY h:mm A zz");
As described in the documentation:
Note: as of 1.6.0, the z/zz format tokens have been deprecated. Read more about it here.
The general problem is that time zone abbreviations are not available from the browser through a consistent API. In order to provide them, one has to have an external source of data.
You may want to look into using the moment-timezone addon. It provides time zone information, including abbreviations. You would have to know the specific time zone you are working with. For example:
moment.tz("2015-08-05T00:00:00+01:00", "Europe/London").format("MM/DD/YYYY hh:mm A z");
// "08/05/2015 12:00 AM BST"
Also, you shouldn't mix HH (hours of the 24-hour clock) with A (the 12-hour am/pm designator). Either use hh with A, or use HH without A.
To Convert UTC datetime to user's current timezone the solution is to use moment-timezone instead of moment.(We have all dates as UTC in DB). Other timezones shouldn't be an issue either.
const timeZoneString = Intl.DateTimeFormat().resolvedOptions().timeZone
const getFormattedDateTimeWithTZ = (date) => {
return moment((date)).tz(timeZoneString).format('ddd, MMM DD YYYY, h:mm A zz')
}
// outputs Tue, Mar 08 2022, 4:00 PM PKT
getFormattedDateTimeWithTZ('2022-03-08T03:00:00.000-08:00')
Related
Considering the following situation:
let record = "2020-04-01 13:33 PM UTC";
var local_date = moment(new Date(record)).format("MMM Do, YYYY h:mm A");
Above code returns invalid date.
But for the following situation:
let record = "2020-04-01 2:33 AM UTC";
var local_date = moment(new Date(record)).format("MMM Do, YYYY h:mm A");
it returns :
Apr 1st, 2020 8:33 AM
Link to sandbox: https://codesandbox.io/s/happy-volhard-m1c7d
Any suggestions to solve this problem ?
If the string you want to parse is not one of the formats supported by moment.js and you don't provide the format, it will use the built–in parser instead. You will have a message in the console warning you that is a bad idea (because it is, see Why does Date.parse give incorrect results?).
When you have any unsupported format string, you must provide the format, e.g.
let s = "2020-04-01 13:33 PM UTC";
// Provide the input format when parsing
let d = moment(s, 'YYYY-MM-DD HH:mm A UTC');
// Provide the output format when formatting
console.log(d.format('MMM Do, YYYY h:mm A'));
// If the date is to be treated as UTC, use .utc
console.log(d.utc().format('MMM Do, YYYY h:mm A'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
BTW, when using 24 hour time, using AM and PM is redundant (and possibly confusing).
The UTC that you're providing is not correct, Either change the MMM Do, YYYY h:mm A to MMM Do, YYYY hh:mm A or change the time first to 12 hr format. The format is expecting 01,11,24 etc.
my system uses timezone UTC+03:00 ,
im trying to get a date in string format, represented by NY timezone,
and convert it to a Date object in utc
const dateInNY = moment.tz(xlsxDate, "M/D/YYYY h:mm a", "America/New_York")
.tz("Z").toDate();
doesnt work correctly
how am i even suppose to convert to utc time?
-----------edit---------------
i got it to work, using the timezone "Africa/Accra" , where UTC offset is 0, and ther is no daylight savings time:
moment.tz(xlsxDate, "M/D/YYYY h:mm a", "America/New_York").tz("Africa/Accra")
but this solution is a bad workaround, and if the government of Accra decide to change the time laws, will stop working!
is there a way to set the utc offset to 0 in momentjs-timezones?
As Álvaro González mentioned, that Date object does not contain Time zone information.
I do the following:
new Date(moment.tz(date, currentTimezone).tz(newTimezone).format('YYYY/MM/DD HH:mm:ss'))
where date is a date object or a string (e.g. '2017-10-30 16:30:00.0000')
so, I change date from currentTimezone to newTimezone and after that new Date object will be returned
Let's change '2017-10-30 16:30:00.0000' from UTC to America/Toronto (UTC-4)
new Date(moment.tz(date, 'UTC').tz('America/Toronto').format('YYYY/MM/DD HH:mm:ss'))
And I got
Mon Oct 30 2017 12:30:00 GMT+0400
GMT+0400 is my timezone and console.log() just shows it with any
date object and it can mislead you. Please, don't look at the this
timezone.
Let's change '2017-10-30 16:30:00.0000' from Europe/Samara (UTC+4) to America/Toronto (UTC-4)
new Date(moment.tz('2017-10-30 16:30:00.0000', 'Europe/Samara').tz('America/Toronto').format('YYYY/MM/DD HH:mm:ss'))
Firstly, moment.tz undertands that date has no timezone information and associate with Europe/Samara (UTC+4)
timezone. After that computes difference between new and old
timezone (it's -8 hours in this case)
And returns result
Mon Oct 30 2017 08:30:00 GMT+0400
And answer on your question
If xsltDate is a date object or string which do not contain timezone information
dateUTC = new Date(moment.tz(xlsxDate, "America/New_York").tz("UTC").format('YYYY/MM/DD HH:mm:ss'));
If xsltDate contain timezone information (e.g.'2013-06-01T00:00:00-04:00'), then no need to tell moment.tz which timezone xlsxDate has, just mention a new timezone
dateUTC = new Date(moment.tz(xlsxDate, "UTC").format('YYYY/MM/DD HH:mm:ss'));
Short answer is that you cannot.
The .toDate() method of the Moment library returns a native Date object. Such objects do not keep memory of any specific time zone (that's one of the reasons to use Moment in the first place), they just keep track of the exact time moment represented and merely pick a time zone when formatting to string, which is either UTC or the browser's time zone (not an arbitrary one).
The long answer is that you're probably getting correct results but are printing them with a method that uses the browser's time zone.
i found a function that does what i was trying to do, it belongs to the momentjs library itself: utcOffset(n) sets the offset to n.
(i also had to explicitly write the date string format correctly, thanks VincenzoC)
this is the code i was trying to write:
const dateInNY = moment.tz(xlsxDate, "M/D/YYYY h:mm a", "America/New_York");
const dateUTC = dateInNY.utcOffset(0).toDate();
however, the toDate function changes the timezone to my local timezone anyway, so .utcOffset(0) is redundat, and i can just use moment this way:
const dateInNY = moment.tz(xlsxDate, "M/D/YYYY h:mm a", "America/New_York");
const dateUTC = dateInNY.toDate();
and change the Date objects date to utc time later (in my case, the JSON.stringify stuff i use later does that for me)
I have a DateTime string like 2/24/2017 17:00:00 which comes from a web service. The time is UTC time. Now i want to convert it to user's local time and display it in browser. And i'm using Moment.js.
I've tried:
var utcTime= moment('2/24/2017 17:00:00' + " +0000", "MM/DD/YYYY HH:mm:ss Z");
var localTime = utcTime.add(new Date().getTimezoneOffset().toString(), 'm').toDate();
It will work but somehow looks strange. Am i missing something? Is there a better way to do this?
Write it like this:
moment.utc('2/24/2017 17:00:00', "MM/DD/YYYY HH:mm:ss").local().format('lll');
Reference: http://momentjs.com/
I want to change a format of a date and time string. But moment.js changes timezone to my system timezone (+3):
// This is a string:
"2013-09-20 23:59:59 +0100"
// I want to change it to this:
"20-09-2013 23:59:59 +0100"
// This is what I do and what I get. 1 hour is added by force:
moment("2013-09-20 23:59:59 +0100").format("DD-MM-YYYY HH:mm:ss ZZ")
"21-09-2013 01:59:59 +0300"
How to just change a format without changing timezone?
See moment issue #887, directly regarding this. It may be easier in a future version, but the current workaround is as follows:
var input = "2013-09-20 23:59:59 +0100";
var m = moment(input).zone(input);
m.format("DD-MM-YYYY HH:mm:ss ZZ")
In moment.js v-2.8.3:
var dateTime = "2014-12-09 13:59:59 +0930";
var parseDateTimeZone = moment.parseZone(dateTime).format("YYYY-MM-DDTHH:mm:ssZ");
Doc-API
I have a string in this format:
var testDate = "Fri Apr 12 2013 19:08:55 GMT-0500 (CDT)"
I would like to use Moment.js get it in this format mm/dd/yyyy : 04/12/2013 for display.
I tried to do it using this method,
moment(testDate,'mm/dd/yyyy');
Which errors and says there is no such method called replace? Am I approaching this in the wrong way?
Edit
I should also mention that I am using a pre-packaged version of Moment.js, packaged for Meteor.js
Object [object Date] has no method 'replace' : The Exact error from the console
Stack Trace:
at makeDateFromStringAndFormat (http://127.0.0.1:3000/packages/moment/lib/moment/moment.js?b4e3ac4a3d0794023a4410e7941c3e179398b5b0:539:29)
at moment (http://127.0.0.1:3000/packages/moment/lib/moment/moment.js?b4e3ac4a3d0794023a4410e7941c3e179398b5b0:652:24)
at populateProfileForEdit (http://127.0.0.1:3000/client/views/home/administration/directory/profiles/profiles.js?acfff908a6a099f37312f62892a22b40f82e5e0f:147:25)
at Object.Template.profile_personal.rendered (http://127.0.0.1:3000/client/views/home/administration/directory/profiles/profiles.js?acfff908a6a099f37312f62892a22b40f82e5e0f:130:13)
at Spark.createLandmark.rendered (http://127.0.0.1:3000/packages/templating/deftemplate.js?b622653d121262e50a80be772bf5b1e55ab33881:126:42)
at http://127.0.0.1:3000/packages/spark/spark.js?45c746f38023ceb80745f4b4280457e15f058bbc:384:32
at Array.forEach (native)
at Function._.each._.forEach (http://127.0.0.1:3000/packages/underscore/underscore.js?867d3653d53e9c7a171483edbcad9670e12288c7:79:11)
at http://127.0.0.1:3000/packages/spark/spark.js?45c746f38023ceb80745f4b4280457e15f058bbc:382:7
at _.extend.flush (http://127.0.0.1:3000/packages/deps/deps.js?9642a93ae1f8ffa8eb1c2475b198c764f183d693:231:11)
The 2nd argument to moment() is a parsing format rather than an display format.
For that, you want the .format() method:
moment(testDate).format('MM/DD/YYYY');
Also note that case does matter. For Month, Day of Month, and Year, the format should be uppercase.
Include moment.js and using the below code you can format your date
var formatDate= 1399919400000;
var responseDate = moment(formatDate).format('DD/MM/YYYY');
My output is "13/05/2014"
moment().format(); // "2019-08-12T17:52:17-05:00" (ISO 8601, no fractional seconds)
moment().format("dddd, MMMM Do YYYY, h:mm:ss a"); // "Monday, August 12th 2019, 5:52:00 pm"
moment().format("ddd, hA"); // "Mon, 5PM"
You Probably Don't Need Moment.js Anymore
Moment is great time manipulation library but it's considered as a legacy project, and the team is recommending to use other libraries.
date-fns is one of the best lightweight libraries, it's modular, so you can pick the functions you need and reduce bundle size (issue & statement).
Another common argument against using Moment in modern applications is its size. Moment doesn't work well with modern "tree shaking" algorithms, so it tends to increase the size of web application bundles.
import { format } from 'date-fns' // 21K (gzipped: 5.8K)
import moment from 'moment' // 292.3K (gzipped: 71.6K)
Format date with date-fns:
// moment.js
moment().format('MM/DD/YYYY');
// => "12/18/2020"
// date-fns
import { format } from 'date-fns'
format(new Date(), 'MM/dd/yyyy');
// => "12/18/2020"
More on cheat sheet with the list of functions which you can use to replace moment.js: You-Dont-Need-Momentjs
var moment = require('moment');
let yourdate = '2021-01-02T07:57:45.121Z'; // for example
moment(yourdate).format('MM/DD/YYYY');
// output : 01-02-2021
moment(yourdate).format('DD-MMM-YYYY');
// output : 01-Jan-2021
For fromating output date use format. Second moment argument is for parsing - however if you omit it then you testDate will cause deprecation warning
Deprecation warning: value provided is not in a recognized RFC2822 or ISO format...
var testDate= "Fri Apr 12 2013 19:08:55 GMT-0500 (CDT)"
let s= moment(testDate).format('MM/DD/YYYY');
msg.innerText= s;
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<div id="msg"></div>
to omit this warning you should provide parsing format
var testDate= "Fri Apr 12 2013 19:08:55 GMT-0500 (CDT)"
let s= moment(testDate, 'ddd MMM D YYYY HH:mm:ss ZZ').format('MM/DD/YYYY');
console.log(s);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
You can pass "L" to format method, which handles internationalisation...
moment.locale('en-US');
moment().format("L");
> "06/23/2021"
moment.locale('fr');
moment().format("L");
> "23/06/2021"
Other long date formats (fr locale):
LT : 'HH:mm',
LTS : 'HH:mm:ss',
L : 'DD/MM/YYYY',
LL : 'D MMMM YYYY',
LLL : 'D MMMM YYYY HH:mm',
LLLL : 'dddd D MMMM YYYY HH:mm'
Docs: https://momentjs.com/docs/#/displaying/format/ (see "Localized formats")
To get the current UTC time in YYYY-MM-DD HH:MM:ss.Millisecond with timezone using moment format as below
moment().utc().format('Y-MM-DD HH:mm:ss.SSS Z').
Output
2022-09-20 15:28:39.446 +0000
May be this helps some one who are looking for multiple date formats one after the other by willingly or unexpectedly.
Please find the code:
I am using moment.js format function on a current date as (today is 29-06-2020)
var startDate = moment(new Date()).format('MM/DD/YY'); Result: 06/28/20
what happening is it retains only the year part :20 as "06/28/20", after If I run the statement :
new Date(startDate)
The result is "Mon Jun 28 1920 00:00:00 GMT+0530 (India Standard Time)",
Then, when I use another format on "06/28/20": startDate = moment(startDate ).format('MM-DD-YYYY'); Result: 06-28-1920, in google chrome and firefox browsers it gives correct date on second attempt as: 06-28-2020. But in IE it is having issues, from this I understood we can apply one dateformat on the given date, If we want second date format, it should be apply on the fresh date not on the first date format result.
And also observe that for first time applying 'MM-DD-YYYY' and next 'MM-DD-YY' is working in IE.
For clear understanding please find my question in the link:
Date went wrong when using Momentjs date format in IE 11