Datepicker date format not comparing with moment date format - javascript

I have a datepicker on a registration page for selecting date of birth. The date picker works fine and if I capture its value (using javascript) it's value is correct (e.g. 4-12-1978)
In my function, which is using moment.js;
function checkBirthdate(dob) {
// dob is coming from $('#validation-dateofbirth').val()
var allowed = false;
var registerDate = moment().add(-18, "years").format("MM-DD-YYYY");
if (dob.isValid()) {
allowed = dob.isBefore(registerDate);
}
return allowed;
}
when testing, dob.isValid is an error. Okay that became obvious, I was trying to compare a moment date with a non moment date. Therefore, I have to convert the datepicker's output to a moment date.
Adding
dob = moment(dob);
//I also tried using
dob = moment(dob, "MM-DD-YYYY");
to the function should've worked, since the passed in dob value was in the same format shown in many moment docs (well, I'm assuming the value from the datepicker is a string like "4-12-2016"), but it doesn't.
How can I convert the value coming from the datepicker (I'm using the bootstrap datepicker) to a moment date?

Related

Get date inside jquery datepicker with not-ISO date format

I'm using jQuery datepicker to set the limit in a time series made with Highcharts for a personal project.
My date format is dd/mm/yyyy.
Following code works for sure till some weeks ago
onSelect: function () {
var minTime = $('input.highcharts-range-selector:eq(0)').datepicker("getDate").getTime();
var maxTime = $('input.highcharts-range-selector:eq(1)').datepicker("getDate").getTime();
}
But now I get following error:
"The specified value "03/02/2021" does not conform to the required format, "yyyy-MM-dd".
Searching I've understood that it depends on the fact that I'm using a format different from the ISO.
How I can fix this issue maintaining my date format?
Bonus question:
What could be changed from the last time that I've checked my site?
Thank you all

Searching in input gives incorrect date in material date picker need to convert it into UTC

I am extending MomentDateAdapter for my requirement. When i am selecting a date from the calendar i am getting the correct output but when i manually type something in the input field i get wrong output.
For the selected date i am using _moment.utc({ year, month, date }).locale(navigator.language); to convert the selected value to UTC format but i am not sure on how to do the same when user searches in the input field.
StackBlitz.
to reproduce:
Try to select a value from calendar and see the console (notice the date is converted to UTC)
Now try to add a date manually by typing in and see the console (date is not converted to UTC).
You need to adapt your parse method call of moment to:
return moment.utc(value, parseFormat, this.locale, true);
to get utc Date from your input.
Here is your adapted Stackblitz.
The methods format and createDate are called if you set your date via picker, the parse method is called if you set it via input.

moment js invalid date from masked input text

Im trying to validate a birthdate with moment js, but i cant do it.
Im using this code:
dateIsBefore(date) {
return moment(date, 'DD/MM/YYYY').isBefore(moment().format('DD/MM/YYYY'));
}
and this is my masked input element:
<el-input
class="date-input"
type="tel"
v-mask="'##/##/####'"
placeholder="dd/mm/aaaa"
></el-input>
but it return me a false value, when i expecting a true. The moment object say the date is invalid.
Im getting the date from an input text (is a masked input date) with the format '28/04/1990'.
I suspect the problem is here:
dateIsBefore(date) {
return moment(date, 'DD/MM/YYYY').isBefore(moment().format('DD/MM/YYYY'));
// --------------------------------------------------^^^^^^^^^^^^^^^^^^^^^
}
You already have a Moment (from moment()), just use it directly, don't convert it to a string:
dateIsBefore(date) {
return moment(date, 'DD/MM/YYYY').isBefore(moment());
}
That definitely makes more sense, and the reason I think it may solve your problem is that if you pass a string in to isBefore, Moment has to parse the string. Without knowing the format, faced with a string in the form ##/##/#### it's almost certainly going to use the (somewhat bizarre) U.S. format, which is MM/DD/YYYY because that's what browsers do (even outside the U.S.) when faced with that kind of string.
Passing in a Moment means you don't have to worry about that.
Its because the input parameter for the method dateIsBefore is in the format of DD-MM-YYYY this is not the valid date format.Your date format should be MM-DD-YYYY and you doesn't want to format the moment functions
Date time string format
Use this method for the date format 'DD-MM-YYYY'
function dateIsBefore(date) {
const dateInput=date.split('-') //use this line of code the input is in the format
of 'DD-MM-YYYY'
return moment(`${dateInput[1]}-${dateInput[0]}-${dateInput[2]}`).isBefore(moment());
}

Parse JSON DateTime object to local time in JQuery by ignoring timezone

I am facing an issue while parsing JSON Date Time object using moment(of course I tried many approaches suggested in Stackoverflow but nothing worked in my case).
In my application, I'm storing a DateTime value as UTC DateTime. Now when I'm displaying I need to display it according to the browser timezone. After going through many StackOverflow questions, I used "moment.js" as below
//From server, the Date object looks like /Date(1506510057813)/
//The equivalent DateTime value stored in Database is 2017-09-27 13:00:57.813
fuction DateTimeFormatter(value)
{
if (value != undefined) {
var newValue = new Date(moment.utc(value));
//But at this line, even with just moment(value) all I am getting is DateTime which is not same as UTC time.
//I don't want any time zone to get appended all I want is just 13:00:57
var newHours = newValue.getHours() - newValue.getTimezoneOffset() / 60;
var newMinutes = (newHours + '.0').split('.')[1] * 6;
newValue.setHours(newHours);
newValue.setMinutes(newMinutes);
return moment(newValue).format(applicationTableDateFormat);
}
else
return "";
}
Please let me know what I am doing wrong or is there any other way I can display time as per browser time zone.
Once you have a UTC moment, you can convert it to local.
moment.utc(value).local().format(...)
https://momentjs.com/docs/#/manipulating/local/
But it sounds like maybe your real problem is when you store the date. If you're storing it as UTC, make sure you actually convert the local value to UTC before you store it. That way when you read it, you get a predictable value that you can safely convert to any locale.
Angularjs has its own mechanism to display formatted dates on views you just needs an absolute representation of a date and it takes care of the rest. And by absolute, I mean, a Date which is settled in a timezone whether it's utc or not, you need to know what timezone you are talking about.
The date filter
It's a filter from the core module of angularjs and it accepts:
"... either as Date object, milliseconds (string or number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.sssZ and its shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is specified in the string input, the time is considered to be in the local timezone." (Angularjs date filter)
The problem
Angularjs need a proper date input in order to display it correctly, in your case you seem to have the milliseconds format (sort of, /Date(1506510057813)/), you could use that and extract the numeric part and input that on the pipe, or you can change the server to send the ISO 8601 date (a.k.a., yyyy-MM-ddTHH:mm:ss.sssZ).
For example:
let rawDate = '/Date(1506510057813)/';
let re = /\/Date\((\d+)\)\//g; // regex to extract number from the string date
let myDate = new Date(Number(re.exec()[1])) // extract the milliseconds
Or
let rawDate = '2017-09-27T11:00:57.813Z';
let myDate = new Date(rawDate)// and you don't need to do anything else
Either way you'd end up with something like this:
<span> {{ myDate | date }}</span>

Create an input type="date" in Ember

I'm trying to create an <input type="date"/> in Emberjs and I have two problems:
In my country the date is displayed as DD-MM-YYYY format while the date field requires a MM-DD-YYYY format (and then the browser displays it according to its locale). So the date should be formatted in one way if the browser supports the date input field and in the other way if not
The date is bound to a Date object
I'm using Momentjs for formatting and Ember Data.
I'm trying to extend Ember.TextField like this:
App.DateField = Ember.TextField.extend
value: ( (key, value) ->
if value?
if /Date/.test value.constructor #I assume that if the passed value is a Date object then it is arriving directly from the model
if Modernizr.inputtypes.date
moment(value).format('YYYY-MM-DD')
else
moment(value).format('DD-MM-YYYY')
else # if the passed value is not a Date object then the user is typing into the form
if Modernizr.inputtypes.date
value = new Date('value')
else
value
).property()
type: 'date'
For browsers with date input supports this works.
For the other browsers the date is correctly displayed, but it is saved as a (wrong formatted) string in the model.
How can I maintain the correct formatting while still using Date objects in the backend?
Demo
Update
Thanks to the blog post provided in the accepted answer I was able to update the demo to do what I want (with some weirdnesses, but not relevant at this time)
Demo2
Have look at these two blog posts:
This is a simple date picker:
http://hawkins.io/2013/06/datepicker-in-ember/
This one uses the bootstrap date picker
http://hawkins.io/2013/06/fancy-ember-datepicker-with-twitter-bootstrap/
Hopefully that will help
I don't see any parsing for the string use case. You will need to use something like Date.parse to convert the string entered by the user into a Date object.
if Modernizr.inputtypes.date
value = new Date(value)
else
value = Date.parse(value)

Categories