Moment getting date attributes mistakenly - javascript

I'm trying to use MomentJS to support dates handling in my application. However, I'm facing a problem with date manipulation.
The files are loaded in this order:
<script src="/javascripts/modules/moment/moment.min.js"></script>
<script src="/javascripts/modules/moment/moment-timezone.min.js"></script>
<script src="/javascripts/modules/moment/moment-timezone-data.js"></script>
<script src="/javascripts/modules/moment/moment-with-langs.min.js"></script>
Now in somepart of my JS code I change the moment language to FR or PT.
moment.lang('fr');
Both languages validade a date as "DD/MM/YYYY" instead of american pattern. So I expect moment
to validate a date following the country date pattern passed.
Then 12/10/2014 must be: day (12), month (09), year (2014), but it is returning always american pattern instead of the correct one.
I'm getting the date properties as:
console.log("DAY: " + moment(textDate).date());
console.log("MONTH: " + moment(textDate).month());
console.log("YEAR: " + moment(textDate).year());
where textDate is my date taken from a text input.
## EDIT ##
I know I can pass the pattern to Moment. I.e:
moment(textDate, 'DD/MM/YYYY');
In the case of my application I'm using like this:
moment(textDate, '<%=lingua.general.time.pDate%>');
However, it suppose to work automatically, don't it? Of course if you already have needed language packages as well. So the previous way I mentioned before should Works, whatever.

If you don't pass any formatting arguments, moment will let your browser do the parsing (with the exception of a full ISO timestamp).
To tell moment to do the parsing, and to use the localized short date format associated with the language, pass an L as the format string:
moment(textDate, 'L')
See in the docs:
Parsing using #String+Format
The display formats. Scroll down to "Localized formats". (The parser uses the same format strings)
Also, not related to your question, but moment-with-langs already includes a copy of moment.js, so you don't need both scripts.

Related

Kind of time (yyyymmddThhmmZ)

I'm trying to generate links to Google calendar and see this tool:
https://decomaan.github.io/google-calendar-link-generator/
And the links are generated as:
https://www.google.com/calendar/render?action=TEMPLATE&text=Appointment+with+VULKOVICH%2C+BILL&details=a+Description&location=a+Location&dates=20210105T103300Z%2F20210114T103300Z
and as you can see the dates are like:
20210105T103300Z
and I am trying to convert this to my own dates but I don't know which type is this and how to format. I have the dates both, in moment or in date, but don't know how to convert.
That's ISO-8601
The first part is the date in year-month-date order, the second part is the time and the final letter indicates the timezone (here Z for 'Zulu')
Since you're using moment.js: moment().utc().format('YYYYMMDDTHHmmss[Z]'), or without a library new Date().toISOString().replace(/\W/g,'').replace(/\d{3}Z/,'Z'). This is really a duplicate of How to format a JavaScript date.
Source: comment by RobG Jan 11 at 12:58

Removing (or allowing) ordinal characters from dynamic text with Date.parse();

I am building a self-depreciating list of dates and am using Date.parse() to convert rich text into a timestamp. Right now, we have a system where the user enters the date themselves, and I use a token on the backend to pull it through to that specific page.
I am trying to 'protect the user' from entering a wrong date format.
Currently, if they enter January 12th, 2016 it won't be able to parse and create a timestamp due to th. However, if they enter January 12, 2016 it can create a timestamp.
Is there a way to replace these ordinal numbers on a dynamic string? I've tried a simple jquery find/replace, but have had no luck with getting it to remove the ordinal date texts.
What I've tried:
$('.my-button').each(function() {
console.log($(this).text());
var text = $(this).text().replace('st, ', '');
$(this).text(text);
});
Any ideas on a solution, or a way to make Date.parse(): accept these extra characters?
For the simple case of removing an ordinal from a date string like "January 12th, 2016", you can use a regular expression like:
var re = /(\d{1,2})[a-z]{2}\b/i;
['January 12th, 2016','January 1st, 2016','January 2nd, 2016','20th February, 2015'].forEach(
function(s) {
document.write('<br>' + s.replace(re,'$1'));
}
);
However, parsing strings with Date.parse (and the Date constructor, they are equivalent for parsing) is strongly recommended against. Use a parser and define the format, do not leave it to chance.
There are libraries like moment.js, however it may be too big for your requirements. There are other dedicated parsers (check on GitHub), or if you only need to support one format, write one yourself. It only requires three or four of lines of code.

Moment failing on some dates

Here are my dates, to me there is no different whatsoever. Yet moment can't handle them all:
console.info(details.date);
console.info(moment(details.date).format());
console.info('________________________________________');
result.date = moment(details.date, "DD-MM-YYYY H:m").format();
//Console
________________________________________
16/10/10 15:00
Invalid date
________________________________________
09/10/10 15:00
2010-09-10T15:00:00+01:00
How can I make my dates safe.
It appears Moment is using the American Date convention, despite it not being documented in there moment(string) interface.
A simple example is here
According to the documentation for moment(string), if a format is not provided when parsing a string it will first try to match one of the ISO 8601 formats specified in ECMA-262. Failing that, it will simply pass the string to new Date(string), which is the same as using Date.parse.
So the result is entirely implementation dependent. However, most browsers will treat nn/nn/nn as a US style date with two digit year, i.e. mm/dd/yy. But that is not guaranteed and may change from browser to browser.
The fix is to always pass the format when parsing strings.
In the second example, the format specified doesn't match the string supplied. It seems it falls back to Date.parse in this case also.
Your date format string uses hyphons ("-") and actual date uses slashes ("/"), so Moment.Js is unable to parse it. Works fine in following example
$("body").text(moment("16/10/10 15:00", "DD/MM/YY H:m").format())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.js"></script>

Getting the proper date from forms that are day/month/year

When writing a new date object with a string, one can write it as:
var someDay = new Date("12/01/2012");
This equals December 1st 2012.
However, what if the user has to fill in a date on a website where the format isn't month/day/year, but day/month/year? How would one go about creating a date object with the correct date then?
If you are getting the data as a string from another website, then you need to know the format in which that website provides you the date. There is no way around this because D-M-Y and M-D-Y are indistinguishable; even Y-M-D would be indistinguishable if they used a two-digit format for the year.
This hasn't been tested at all, but at worst the general idea should solve your problem.
var pattern = /^(\d+)\b(\d+)\b(\d+)$/;
if (!pattern.test(dateString))
return null;
var matches = dateString.match(pattern);
if (siteUsesDMY)
return new Date(matches[2], matches[1]-1, matches[0]);
if (siteUsesMDY)
return new Date(matches[2], matches[0]-1, matches[1]);
...
Pattern: This pattern supports any numeric representation of the date, assuming it has a breaking character between each unit. If you need to support a website that doesn't have a breaking character, you would need a different pattern that matched that website's exact format (i.e.: site sends DDMMYYYY, then pattern would be /^(\d{2})(\d{2})(\d{4})$/).
Also fixed the month parameter in date creation, as I just remembered that JavaScript uses 0-11 for months.

JSON datetime between bash script and JavaScript

In the same spirit as discussed here, is there a recommended way to generate / parse dates from within a bash script so that it can be interfaced to Javascript Date?
To be precise, I get this strings when doing json encoding of a Javascript Date object:
2011-10-31T10:23:47.278Z
I could put together a bash hack to generate / parse that date format, but I would prefer to avoid reinventing the wheel. Does somebody have a working solution?
I am more interested in the "generating" side: I want to generate current dates from a bash script and save them in a json document (couchdb) so that they can be automatically ordered by the view engine.
The closest I am coming is this:
date -u +"%FT%T.000Z"
Which gives this output:
2011-11-03T06:43:08.000Z
I do not like that I have to put the T, the Z and the milliseconds to 0 manually (I can use %N for nanoseconds, and truncate with sed or whatever, but seems like overkill just to get millisecond precission), and I was hoping that there would be a built-in format token for date which would produce that UTC date. I assumed - wrongly it seems - that the format is common enough that it can be specified with just one format token.
JavaScript can convert many different values into dates. Not sure if that's what you mean, but for example. Your bash could generate this string: "2011/11/10 08:08:08"
When it gets to JavaScript land you can do this
var date = new Date("2011/11/10 08:08:08")
You can also do this:
var now = 1320287813362
var date = new Date(now)
More info on what Date accepts here:
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date
Other interesting info here:
What's the best way to store datetimes (timestamps) in CouchDB?

Categories

Resources