facebook-squared twitter-squared rss-squared gplus-squared

Challenges with JavaScript date and Ionic ion-datetime

Written by on 23 December 2017



December 2017



Javascript date and ionic ion-datetime

Dealing with JavaScript has never been easy for me. In JavaScript Today’s date is represented as 2017-11-23. It’s December but no where you can find 12 in it. That’s because months in JavaScript starts from “Zero”. That’s first confusion for you.

Ionic comes with ion-datetime component which lets you easily choose date and time. With native UI and feel for your mobile. Under the hoods it works just like input of type datetime-local

Which means that it accepts [ngModel] and (ionChange) event along with it’s own properties like displayFormat=”MM/DD/YYYY” and pickerFormat. Both of them have difference purpose, one is for display and other one is in which format you want to pick the date.

What if I want to restrict user from reserving a restaurant table for tomorrow. There is property for that, max and it accepts string. So if you pass it today as maximum date, it will disable all the days in the future. Just like in the following screenshot.

ion-datetime ionic date picker

I tried to pass new Date() but it’s a JavaScript Object and I need a string. We can convert any date to string by using the ISOString method (here ISO uses ISO 8601).

var myDate = new Date();
// Sat Dec 23 2017 07:49:45 GMT+0500 (Pakistan Standard Time)

var myDateString = new Date().toISOString();
// "2017-12-23T02:50:42.945Z"

Next we need to extract the date part with year, month and day. Let’s how we can achieve this from date object and date string respectively

var dateFormat = `${myDate.getFullYear()}-${myDate.getMonth()+1}-${myDate.getDate()}`;
// 2017-12-23

Now let’s go with ISO string. As it’s a standard which is unlikely to change, so we can rely on it’s order. Like first comes the date than time

var dateFormat = myDateString.split(0,10)
// 2017-12-23

The problem with above solution is that you have to keep those numbers like start and end index in your head.

Perfect Solution

I think we can do better than that. We use a split function, which will split a string and convert it to an array. Then the first index of an array will have the intended result;

var dateFormat = myDateString.split('T')[0];
// 2017-12-23

We can also go with the date defacto library like momentjs and use it like moment().format(‘YYYY-MM-DD’). But for this little example we can go with vanilla JS.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: