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

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/

Related

moment.js cannot convert actual month into other format

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');

MomentJS: how to parse dates in MM/DD/YYYY & DD/MM/YYYY

How can i use moment.js in both: Australia & USA time formats?
For example:
07/08/2017 - is good for both time formats, but!
30/08/2017 - is invalid for moment.js, but i can have such dateTime
You can check it here:
http://jsfiddle.net/rLjQx/2135/
The parser is assuming that digits of the form XX-XX-XXXX are representing DD-MM-YYYY. If you'd like it to accept MM-DD-YYYY then you need to specify this.
eg var now2 = moment('08/30/2017', 'MM-DD-YYYY').format('MMM DD h:mm A');
You can also specify an array of different formats that you'd like it to accept so that it will recognise both:
var now2 = moment('08/30/2017', ['DD-MM-YYYY', 'MM-DD-YYYY']).format('MMM DD h:mm A');
Specify the format via a second parameter to the moment call
var now2 = moment('30/08/2017', 'DD/MM/YYYY').format('MMM DD h:mm A');
Otherwise there is no way for moment to know
Related docs here: https://momentjs.com/docs/#/parsing/string-format/
Corrected fiddle: http://jsfiddle.net/wu6wwsvp/
In your fiddle you are using a very old version of moment (2.2.1), I suggest to upgrade it to lastest one (2.18.1).
Using a newer version, you will have a Deprecation Warning in your console:
Deprecation warning: value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are discouraged and will be removed in an upcoming major release. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.
Following the link (and moment(String) docs) you will discover that you have to specify format to parse you string correctly.
As Billy Reilly suggested you can use moment(String, String[]) parsing function. Please remeber that:
Starting in version 2.3.0, Moment uses some simple heuristics to determine which format to use. In order:
Prefer formats resulting in valid dates over invalid ones.
Prefer formats that parse more of the string than less and use more of the format than less, i.e. prefer stricter parsing.
Prefer formats earlier in the array than later.
So the way 07/08/2017 will be interpreted depends on the order of the format in array of formats parameter.
Here a snippet with some examples:
var now = moment('30/08/2017', ['MM/DD/YYYY','DD/MM/YYYY']);
var now2 = moment('08/30/2017', ['MM/DD/YYYY','DD/MM/YYYY']);
var now3 = moment('07/08/2017', ['MM/DD/YYYY','DD/MM/YYYY']);
console.log(now.format('MMM DD h:mm A')); // Aug 30 12:00 AM
console.log(now2.format('MMM DD h:mm A'));// Aug 30 12:00 AM
console.log(now3.format('MMM DD h:mm A'));// Jul 08 12:00 AM
var now4 = moment('30/08/2017', ['DD/MM/YYYY','MM/DD/YYYY']);
var now5 = moment('08/30/2017', ['DD/MM/YYYY','MM/DD/YYYY']);
var now6 = moment('07/08/2017', ['DD/MM/YYYY','MM/DD/YYYY']);
console.log(now4.format('MMM DD h:mm A')); // Aug 30 12:00 AM
console.log(now5.format('MMM DD h:mm A')); // Aug 30 12:00 AM
console.log(now6.format('MMM DD h:mm A')); // Aug 07 12:00 AM
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>

Moment.js with a format zulu and format date javascript

I have this format date:
01Mar-0234
26Feb-0430
01 is day, mar or feb is mounth and 0430 is 4 oclock 30 in formater zulu +00.
I would like to use moment for converting this format, I'm trying this:
moment('26Feb-0430').format("DD-MM-YY HH:MM");
but I haven't good format and I have this error :
Deprecation warning: value provided is not in a recognized RFC2822 or ISO format. moment c
onstruction falls back to js Date(), which is not reliable across all browsers and version
s. Non RFC2822/ISO date formats are discouraged and will be removed in an upcoming major r
elease. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.
Arguments:
Can you help me for have 26/02/2017 06:30 for summer and 5h30 winter?
As suggested in the comments and in the warning message you have to use moment(String, String) parsing function.
In the format string parameter you have to use moment tokens where: DD is day of the month. MMM is month's short name, HH is 0-23 hours and mm (lowercase) is minutes.
Since you have to threat your input as +00:00, you have to use moment.utc.
Use format() to display the parsed moment object passing the tokens you need, always remember that moment tokens are case sensitive.
Here a working sample:
var result = moment.utc('26Feb-0430', 'DDMMM-HH:mm').format("DD/MM/YYYY HH:mm");
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>

How can I set up a correct format while doing new Date() in jQuery?

I have a date in a following format:
12/11/2015 07:12 PM
In jQuery I'm doing:
var parsedDate2 = new Date(date);
alert(parsedDate2);
And that prints me:
Fri Dec 11 2015 07:12:00 GMT+0100 (Central European Standard Time)
and that almost works correctly, mostly because in my example (12/11/2015 07:12 PM) the format is DD/MM and not MM/DD. However, jQuery treats it as the month is first. That's a problem, because when I chose as input:
19/11/2015 07:17 PM <--- (19th of November)
I'm getting:
Invalid date
So how can I set up the correct format here with the day before the month?
Ugly, but it work, with JS only :
a = "12/11/2015 07:12 PM";
b = a.split(' ');
c = b[0].split('/');
bad = new Date(a);
alert('bad : '+bad);
good = new Date(c[1]+'/'+c[0]+'/'+c[2]+' '+b[1]+' '+b[2]);
alert('good : '+good);
The other way is to use Moment.js parsing tool
Think that you should use more specialized and focused library along with JQuery, for me the best one is Moment.js - it has all and more than needed to date-time parsing and formatting and doesn't do something else.
Also, there are some other alternatives, like date.js and globalize.js
It's in the form of mm/dd/yyyy. Try 11/19/2015 07:17 PM. Sadly, jQuery doesn't know which format you're using and so, uses the deafult one.
Unfortunately, the Javascript Date system isn't very malleable when it comes to adding date formats. Here is a reference from Mozilla. I think wierdpanda has the right idea, write a function that accepts your date format, reformats it before feeding it to new Date(), and returns the result. Use this in place of where you have new Date(), and all should be good.

Any way to parse a time string using Moment.js but ignore timezone info?

Given the volume of Timezone questions, I would have thought to be able to find the answer to this issue, but haven't had any success.
Is there a way using moment.js to parse an ISO-8601 string but have it parsed in my local timzeone? Essentially I want to ignore the timezone information that is supplied in the ISO string.
For example, if I am in EDT timezone:
var x = moment( "2012-12-31T00:00:00+0000" );
will give me:
"2012-12-30T19:00:00-5000"
I'm looking to ignore the timezone info and just have it give me a moment equivalent of "2012-12-31T00:00:00-5000" local time (EDT).
I don't think you really want to ignore the offset. That would ultimately just be replacing the offset you provided with one from your local time zone - and that would result in a completely different moment in time.
Perhaps you are just looking for a way to have a moment retain the time zone it was given? If so, then use the moment.parseZone function. For example:
var m = moment.parseZone("2012-12-31T00:00:00+0000");
var s = m.format(); // "2012-12-31T00:00:00+00:00"
You could also achieve this with moment.utc. The difference is that moment.parseZone will retain whatever offset you give it, while moment.utc will adjust to UTC if you give it a non-zero offset.
I solved this by supplying a format as the second argument, and using Moment's method of escaping characters, and wrapped square brackets around the timezone.
moment("2016-01-01T05:00:00-05:00", "YYYY-MM-DDTHH:mm:ss[Z]").startOf("hour").format()
This will still create moment objects using your local time zone, but it won't do any sort of auto-timezone calculation. So the above example will give you 5am regardless of timezone supplied.
I know I'm late to the party, I had the same question and my searches didn't bring me any closer. I broke down and read the documentation and there is an option in moment for a String + Format:
String + Format docs
moment(String, String);
moment(String, String, String);
moment(String, String, Boolean);
moment(String, String, String, Boolean);
and more words, then this:
Unless you specify a time zone offset, parsing a string will create a date in the current time zone.
moment("2010-10-20 4:30", "YYYY-MM-DD HH:mm"); // parsed as 4:30 local time
moment("2010-10-20 4:30 +0000", "YYYY-MM-DD HH:mm Z"); // parsed as 4:30 UTC
The part that gave me pause was the example that was used to parse local time omitted the +0000, which lead me to think the input string needed to have that removed, but it doesn't.
example:
var time = "2012-12-31T00:00:00+0000";
var x = moment(time); // Sun Dec 30 2012 19:00:00 GMT-0500
var y = moment(time,'YYYY-MM-DD'); //Mon Dec 31 2012 00:00:00 GMT-0500
You can ignore the browser's timezone completely by creating a new moment using moment.utc() instead of moment().
For example, if you are trying to work purely with a UTC date/time of the browser's current time but want to discard its timezone data, you can recreate the browser's current time into a UTC format using the following:
let nowWithTimezone = moment();
let nowInUtc = moment.utc(nowWithTimezone.format('MM/DD/YYYY HH:mm'), 'MM/DD/YYYY HH:mm');
Further documentation on moment.utc(): https://momentjs.com/docs/#/parsing/utc/
If you know for sure your input string is in the ISO-8601 format, you could just strip off the last 5 digits and use that in the Moment constructor.
var input = "2012-12-31T00:00:00+0000"
input = input.substring(0, input.length-5)
moment(input).toString()
> "Mon Dec 31 2012 00:00:00 GMT-0600"
There are valid reasons to do what the OP is asking for. The easiest way to do this with Moment is using its parseZone(date) method. No futzing around with string manipulation or multiple calls. It effectively parses the date string as though it were in the browser's local time zone.
This is difficult task to do with MomentJS, it will basically depend as well on your current timezone.
Documentation as well is vague for this specific task, the way I solved the issue on my side was by adding hours to the date before converting it to JSON format.
var dt = moment("Sun Sep 13 2015 00:00:00 GMT-0400", "ddd MMM DD YYYY HH:mm:ss GMT-0400", false);
var date = dt.add(2, 'hour').toJSON();
console.log(date); //2015-09-13T00:00:00.000Z
Momentjs default logic will format the given time with local timezone. To format original date, I wrote a function:
https://github.com/moment/moment/issues/2788#issuecomment-321950638
Use moment.parseZone to convert without taking into account the timezone.
const moment = require('moment')
const dateStr = '2020-07-21T10:00:00-09'
const date = moment.parseZone(dateStr)
console.log(date.format('MM-DD-YY HH:mm A')) // 07-21-20 10:00 AM
Try here link to docs
The best way is to use:
dt = moment("Wed Sep 16 2015 18:31:00 GMT-0400", "ddd MMM DD YYYY HH:mm:ss GMT-0400",true);
And to display convert again to desired timezone:
dt.utcOffset("-04:00").toString()
output > Wed Sep 16 2015 18:31:00 GMT-0400

Categories