moment.js cannot convert actual month into other format - javascript

Right now im using the datetimepicker for bootstrap 4
Everything fine so far. I use format LLLL to display the date like this
"moment().format('LLLL'); // Thursday, May 17, 2018 11:57 AM"
This is also working.
Now for saving the data in my MySQL database I want to convert it in the YYYY-MM-DD HH:mm:ss format
The funny thing this is normally working good, but as soon I have date of the the actual month it is not working anymore.
Here is the ouput of my function:
a = Donnerstag, 4. Mai 2017 09:00
Zeit Datenbank ist adb: Invalid date
b = Donnerstag, 13. April 2017 09:00
Zeit Datenbank ist bdb: 2017-04-13 09:00:00
I have two datetimepickers (a & b). Any idea why converting May is not working?
Edit:
January not working
March not working
May not working
December not working
All other months are working!
Code I'm using:
var a=document.getElementById("datetimepicker_start").value;
(to read: a = Donnerstag, 7. Februar 2019 12:53)
var adb = moment(a).format("YYYY-MM-DD HH:mm:ss");
(to convert: Zeit Datenbank ist adb: 2019-02-07 12:53:00)

You need to:
Specify the format of the date you're reading
Include the necessary locale
Using moment without extra args will parse dates based on a limited number of formats, but you can tell it exactly how to parse the given dates by passing an extra argument.
In your case you're reading German, you can include the German locale from here https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/locale/de.js.
e.g.
var a = 'Donnerstag, 4. Mai 2017 09:00'
var adb = moment(a, 'LLLL').format("YYYY-MM-DD HH:mm:ss");
console.log(adb);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/locale/de.js"></script>
To be completely explicit, you can also specify the locale when you're reading a date:
moment(a, 'LLLL', 'de');

Related

Displaying a localized JS Date without timezone adjustment

My Angular front-end is getting timestamps via REST requests to a server in the same timezone. The server does not store timestamps in UTC.
I want to :
display the date and time in a localized way
keep the exact same time displayed (I don't want any timezone adjustments)
For example:
timestamp string from server : 2017-09-20T17:45:00
I need to display it localized like this:
mercredi 20 septembre 2017 17:45 (french)
Wednesday, September 20th, 2017 5:45 PM (english)
On 2 different machines, I get different results, even though the OS is configured with the same timezone :
(UTC+01:00) Brussels, Copenhagen, Madrid, Paris
On machine 1:
Wednesday, September 20th, 2017 6:45 PM // (english) KO !!
On machine 2:
Wednesday, September 20th, 2017 5:45 PM // (english) OK
Currently, the code is:
jsDate = new Date(dateTimeStr);
localizedDateTime = moment(jsDate).local().format('LLLL');
What would be a safe way to always get 5:45 PM ?
Thanks
You're using moment wrong.
Native javascript Date won't necessarily parse that string properly.
Moment will.
From the moment docs String + Format.
localizedDateTime = moment(dateTimeStr, "YYYY-MM-DDTHH:mm:ss").local().format('LLLL');

Moment.js Sql Date Time Conversion with Nodejs

i am using nodejs to connect to mySql and connection works.
while using query such as
SELECT * from someTable
i get the required results. But the problem is that i am having
a column which stores date is having the given format.
before sending the data i need this format to be converted and vice versa
file_date : Wed Jan 01 2014 05:34:53 GMT+0530 (IST)
This is format i am getting
i am unable to send params with Date in this format from client side
so i need to convert this data to "DD-MM-YYYY" format.i need this way so that i can pass params in "DD-MM-YYYY" and fetch data date wise
Simple Approach
If you know your date format is supported in Moment, then the simplest approach is to construct a moment object and format it.
var file_date = 'Wed Jan 01 2014 05:34:53 GMT+0530 (IST)';
var formatted = moment(file_date).format('DD-MM-YYYY');
Deprecation Warning:
However, at some point support for non ISO date formats was deprecated. It will in some cases still work but you should be warned (per the deprecation warning message):
Deprecation warning: value provided is not in a recognized ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non ISO date formats are discouraged and will be removed in an upcoming major release.
Workaround
Instead, if you know the format of an input string, you can use that to parse a moment.
var s = 'Wed Jan 01 2014 05:34:53 GMT+0530 (IST)';
var m = moment(s, 'ddd MMM DD YYYY hh:mm:ss [GMT]ZZ').format('MM-DD-YYYY');
console.log(m);
<script src="https://momentjs.com/downloads/moment.min.js"></script>
When specifying a format manually like this, it helps to have the format documentation handy: https://momentjs.com/docs/#/displaying/format/

Date format - momentjs - extract date and time separately using locale language

I am using moment.js library
I have a date in this format :
2014-08-07T10:00:00+02:00
I want to have two separate values :
- Thursday, August 7 2014
- 10 am
But I also want them to be using the local language.
For example, if moment.lang("fr"), the output should be
- Jeudi 7 Août 2014
- 10h
I set the moment.js lang in the correct way.
I managed to remove hour,minutes and seconds (to extract the first value) :
new Date(moment.utc(date).format('LL')) //Outputs Thu Aug 07 2014 00:00:00 GMT+0200 (Paris, Madrid)
But I don't know how to extract the hour and minutes (for the second value) and how to show the date using the current language.
#Rayjax solution is not working anymore in recent versions of moment.js. Behavior of moment.localeData().longDateFormat() changed. LT is now already replaced by time format. Instead of dddd, MMMM D, YYYY LT it returns now dddd, MMMM D, YYYY h:mm A. Therefore removing LT from string does not work anymore. But we could just remove compiled LT for current locale:
moment.localeData().longDateFormat('LLLL')
.replace(
moment.localeData().longDateFormat('LT'), '')
.trim();
Trim is necessary to avoid unnecessary white spaces.
Hi I don't know if it's the best way do to it but it's working
moment.locale("en");
var now = moment()
console.log(now.format(moment.localeData().longDateFormat('LLLL').replace('LT' , '')));
console.log(now.format(moment.localeData().longDateFormat('LT').replace('mm' , '').replace(':' , '').replace('.' , '')))
http://jsfiddle.net/yann86/tb0u5eav/
I came up with this which works well :
moment.lang("fr"); //en, es or whatever
var date = moment(dateParam).format("LL"),
time = moment(dateParam).format("LT");
console.log(date, time) -- outputs separatedly date and time in the correct language form
What I was missing were the language configs files : http://momentjs.com/ i grabbed momentjs+locales instead of moment.js only and it worked.
It is important to note that moment.js won't tell you you are missing those filed, it will just default to english.
It worked for my needs:
moment().locale('en').format('L');
moment().locale('pt-br').format('L');
Just change the format for your needs. The Documentation of the moment is great. http://momentjs.com/

moment.js converting epoch date to specific timezone

I've been looking for days to find how to get moment.js to behave correctly and return the correct date for a specific local time zone.
Here is my challenge:
I'm calling a flight api to get the "arrival date/time" of a flight. It provides me the arrival time in epoch time and a timezone for the airport.
I'm using javascript moment.js to convert that to the local time of the airport, BUT, the time always comes in a couple days ahead.
Here's my code:
var dateVal = 1395184260;
var day = moment.unix(dateVal).tz('America/Vancouver').format();
console.log("tz :",day);
// should return: 4:21 PM - Sun Mar-16-2014 BUT it always returns the 18th instead of the 16th.
Where are you getting the "should return" from?
According to http://www.epochconverter.com/epoch/timezones.php?epoch=1395184260, your time should be
Mar 18 2014 16:11:00 GMT-7:00
This fiddle using your timestamp:
var dateVal = 1395184260;
var date = moment.unix(dateVal);
console.log(date.tz("America/Vancouver").format('ll HH:mm:ss Z'))
returns:
Mar 18 2014 16:11:00 -07:00
I'd check whatever converter you're using to see if there's a bug.

How to create time in a specific time zone with moment.js

I have this backend that sends me a pre formatted time in a set time zone, but without any information for the said time zone. The strings are like: "2013-08-26 16:55:00".
I can create a new moment.js instance with this string:
var time = moment("2013-08-26 16:55:00") //this creates time in my tz
but this will only create an instance in my own time zone.
Moment.js have a plugin that can create instances of the object in specific time zones and it works great, but I can't say what time I want the object to point to.
If I'm in New York and I do this:
var time = moment("2013-08-26 16:55:00").tz("America/Los_Angeles");
the resulting time will be 13:55 instead of 16:55 but in LA.
What I want is to create an instance that will say 16:55, but in LA time.
The reason I'm asking is because I want to do this:
var now = moment.tz("America/Los_Angeles");
var end = moment("2013-08-26 16:55:00"); //plus something to convert LA time
var timeLeft = end.diff(now, "minutes");
Is there a way to do that?
In most cases, you can simply do this:
moment.tz("2013-08-26 16:55:00", "America/Los_Angeles")
If you require input other than ISO8601, then specify the format string as the second parameter, and the time zone as the third:
moment.tz("8/26/2013 4:55 pm", "M/D/YYYY h:mm a", "America/Los_Angeles")
And if you need to use moment's "strict parsing" mode, then that goes in the third parameter, and the time zone moves to the fourth position:
moment.tz("8/26/2013 4:55 pm", "M/D/YYYY h:mm a", true, "America/Los_Angeles")
If you want to calculate everything in a specific timezone you want to set the default time zone using
A) moment.tz.setDefault("America/Los_Angeles");
For my use case (in a node.js project) I just set it right after requiring the moment modules like so:
let moment = require('moment');
require('moment-timezone');
moment.tz.setDefault("America/Los_Angeles");
All calls to moment() thereafter will create the time in the "America/Los_Angeles" setting, which is NOT the same as using:
B) moment.tz("2017-03-04 00:00", "America/Los_Angeles")
OR
C) moment("2017-03-04 00:00").tz("America/Los_Angeles")
both of which would create the moment object in UTC time (unless you already changed the default), and then convert it to be the Los Angeles timezone.
Running B or C above in the browser console yields:
_d: Fri Mar 03 2017 16:00:00 GMT-0800 (PST)
_i: "2017-3-4 00:00"
Notice _d shows March 3 4:00pm; this is because the moment object is created with March 4 12:00am in UTC time, then converted to Pacific timezone, which is 8 hours behind/the previous day.
source: http://momentjs.com/timezone/docs/#/using-timezones/default-timezone/
install moment-timezone
> npm install moment-timezone
Or see https://momentjs.com/timezone/docs/
.tz(string, string)
moment.tz("2020-01-02 13:33:37", "Iran/Tehran")
Just to make something abundantly clear, that is implied in other answers but not really stated:
You absolutely must either
use ISO8601 as your date format or
specify the format your string is in
.. when using the .tz(string datetime, [string format,] string zone) function, if you want moment to interpret the datetime argument you give to be in the zone you give. If you omit format, be sure to pass an ISO8601 formatted string
For 2 days I went round in circles, because my API was delivering a time string like "03 Feb 2021 15:00" and sure, it parsed OK, but it always used the timezone from my local machine, then converted to the timezone I gave:
//this always resulted in "2021-02-03 10:00 EST" if run on a machine in UTC
moment.tz("03 Feb 2021 15:00", "America/Indianapolis").format("YYYY-MM-DD HH:mm z")
This was massively confusing: the parsing was clearly working fine, because the date was right but the time was always wrong by however many hours there were between the machine and the given zone string
Switching to ISO format input worked:
//this always resulted in "2021-02-03 15:00 EST" if run on a machine in UTC
moment.tz("2021-02-03 15:00", "America/Indianapolis").format("YYYY-MM-DD HH:mm z")
As did declaring:
//this always resulted in "2021-02-03 15:00 EST" if run on a machine in UTC
moment.tz("03 Feb 2021 15:00", "DD MMM YYYY HH:mm", "America/Indianapolis").format("YYYY-MM-DD HH:mm z")
I hope this saves someone some time
I had a similar issue for which i had to use New York based time so i had to consider for daylight savings. I tried using the above few answers but wasn't able to get it working. Then I solved my issue like the below code
import moment from 'moment-timezone'
const time = timestamp
const offset = moment.tz.zone('America/New_York')?.parse(time)
const date = moment(time).add(offset, 'minutes').toISOString()
or you can do this way which will consider the time offset on its own when you display locally.
const time = moment.tz(timestamp, 'America/New_York')
const localtz = moment.tz.guess()
const date = time.clone().tz(localtz)
this gives you an ISO string which you can use as below
moment(date).local().format('dddd, MMM DD YYYY, hh:mm A')
or in whatever format you would like to display it

Categories