DateTime - default to todays date


I thought that my scenario wouldn’t be the same as the original asked therefore i didn’t post it, but it if it can be useful here it go:

install with

npm install date-fns --save


import {format} from 'date-fns/esm';


  loadAvailabilities(): Promise<any> {
     return new Promise( (resolve, reject) => {
    this.db.listAvailabilities(this.exKey).then((snapshot) => {
      this.availabilities = [];
      snapshot.forEach(snap => {
          key: snap.key,
          dateStart: format(snap.val().dateStart, 'dddd, DD MMMM HH:mm:ss'),
          dateEnd: format(snap.val().dateEnd, 'dddd, DD MMMM HH:mm:ss'),
          adults: snap.val().adults,
          kids: snap.val().kids,
          status: snap.val().status
        return false
    //    this.loader.hidePreloader();

HTML: (* I know availability wasn’t the best word to use here lol)

  <ion-card *ngFor="let availabilitie of availabilities" padding>

     <ion-note> Start </ion-note> <ion-label> {{availabilitie.dateStart}} </ion-label>
     <ion-note> Finish </ion-note> <ion-label> {{availabilitie.dateEnd}}  </ion-label>
     <ion-note> Adults </ion-note> <ion-label>{{availabilitie.adults}} </ion-label>
     <ion-note> Kids</ion-note> <ion-label>{{}} </ion-label>

          <button ion-button icon-left clear small color='danger'>
            <ion-icon name="trash"></ion-icon>


The documentation is quite good at their website, i’ve started developing 1 month ago and manage to do it.


i tried it and it also display current date on screen but when i print the vale of myDate on console then it represent current date in ISO format.So how can change its ISO format to another?


I had different use cases.

  1. I can not set default value for my model object because I need to take care resetting model value when user tap cancel from picker.
  2. I want to pre select today date in picker when user don’t have default model value. So that user can simply tap done button for picking today value.

Initially I thought of extending DateTime component and adding my functionality over there. But it was not easy because the selection is happening when ionic generate DateTime picker options. Finally I end up in changing ionic source code (datetime.js).

DateTime.prototype.generate = function () {
        var _this = this;
        var /** @type {?} */ picker = this._picker;
        // if a picker format wasn't provided, then fallback
        // to use the display format
        var /** @type {?} */ template = this.pickerFormat || this.displayFormat || DEFAULT_FORMAT;
        if (isPresent(template)) {
            // make sure we've got up to date sizing information
            // does not support selecting by day name
            // automaticallly remove any day name formats
            template = template.replace('DDDD', '{~}').replace('DDD', '{~}');
            if (template.indexOf('D') === -1) {
                // there is not a day in the template
                // replace the day name with a numeric one if it exists
                template = template.replace('{~}', 'D');
            // make sure no day name replacer is left in the string
            template = template.replace(/{~}/g, '');
            // parse apart the given template into an array of "formats"
            parseTemplate(template).forEach(function (format) {
                // loop through each format in the template
                // create a new picker column to build up with data
                var /** @type {?} */ key = convertFormatToKey(format);
                var /** @type {?} */ values;
                // first see if they have exact values to use for this input
                if (isPresent(((_this))[key + 'Values'])) {
                    // user provide exact values for this date part
                    values = convertToArrayOfNumbers(((_this))[key + 'Values'], key);
                else {
                    // use the default date part values
                    values = dateValueRange(format, _this._min, _this._max);
                var /** @type {?} */ column = {
                    name: key,
                    selectedIndex: 0,
                    options: (val) {
                        return {
                            value: val,
                            text: renderTextFormat(format, val, null, _this._locale),
                // cool, we've loaded up the columns with options
                // preselect the option for this column

                var /** @type {?} */ optValue = getValueFromFormat(_this.getValue(), format);
                //If we get empty date value from source..needs to select today in date picker.
                if(!(_this._value && && _this._value.month && _this._value.year)) {
                  var today = new Date();
                  optValue = getValueFromFormat({
                    day: today.getDate(),
                    month: today.getMonth()+1,
                    year: today.getFullYear()
                  }, format);

                var /** @type {?} */ selectedIndex = column.options.findIndex(function (opt) { return opt.value === optValue; });
                if (selectedIndex >= 0) {
                    // set the select index for this column's options
                    column.selectedIndex = selectedIndex;
                // add our newly created column to the picker
            // Normalize min/max
            var /** @type {?} */ min_1 = (this._min);
            var /** @type {?} */ max_1 = (this._max);
            var /** @type {?} */ columns_1 = this._picker.getColumns();
            ['month', 'day', 'hour', 'minute']
                .filter(function (name) { return !columns_1.find(function (column) { return === name; }); })
                .forEach(function (name) {
                min_1[name] = 0;
                max_1[name] = 0;

It would be nice, when we have some attribute in DateTime component for selecting default value in picker.

Now my problem is, I need to inform my co developers to update this function every time and same thing with updating node modules. I need to take care of maintaining this change now.

I am looking some other good solution.

Thanks in advance!!


Hi @esisuriyan,

If you have Object errors like “undefined” or “null” you can try another approach using *NgIf in the template (html file).

Also, developers advice to use moment.js if you need complex calendars, I haven’t tried it yet, but it seems the best solution I have seen.

Finally, I looked at html5 datetime-local function, to check if it could be integrated in my app, and the end result is not bad. But I didn’t made the CSS / SCSS to style it inside a ion-card or ion-item to test.

Happy coding :slight_smile:


My friend, if I want to use this format in component and not html for example

myDate: String = new Date().toISOString();

  ngOnInit() { 
    outpu = 2018-05-11T14:20:33.173Z

get this item and format in time my country 11/05/2018 and time, any idea ?


I, too, had the problem with the default timezone being set to GMT, when the picker opens.

Fortunately, ion-datetime apparently has an undocumented attribute called initialValue. So, if you want to get a different timezone, you can do this:

<ion-datetime [initialValue]="myInitialTime" pickerFormat="HH:mm" [(ngModel)]="myTime"></ion-datetime>

And in your .ts file, you can init the value in the constructor or somewhere else:

this.myInitialTime = '10:30'; // or do some real date calculations

This way, your model (myTime) remains clean.


You just saved my life!


Melchia, Thank you very much. Got stuck on this problem for a few hours now. Now it works flawlessly. Thanks!


@rafaelmoura use moment.js plugin to get current date and time.