DateTime - default to todays date


#42

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

and

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

TS:

  loadAvailabilities(): Promise<any> {
     return new Promise( (resolve, reject) => {
    this.db.listAvailabilities(this.exKey).then((snapshot) => {
      console.log(snapshot);
      this.availabilities = [];
      snapshot.forEach(snap => {
        this.availabilities.push({
          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
      });
      resolve(this.availabilities);
    //    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>{{availabilitie.kids}} </ion-label>

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

  </ion-card>

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


#43

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?


#44

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
            this.calcMinMax();
            // 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: values.map(function (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.day && _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
                picker.addColumn(column);
            });
            // 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 column.name === name; }); })
                .forEach(function (name) {
                min_1[name] = 0;
                max_1[name] = 0;
            });
            this.divyColumns();
        }
    };

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!!


#45

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:


#46

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

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

  ngOnInit() { 
    console.log(this.myDate('mm/dd/YYYY'));
    outpu = 2018-05-11T14:20:33.173Z
  }

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


#47

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.


#48

You just saved my life!


#49

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


#50

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