Set ion-datetime default to device time

Hi Ionic-Community,

I’m fairly new to Ionic 2, and Ionic in general. At the moment I’m building my second app to get a little bit more into the material. Today I came a cross an issues that I think most of the developers stumble upon.

In the app I’m build right now the user has the opportunity to create time spans which have a starting and end datetime. Of course I’m using the ion-datetime-component but it is kind of strange to me.

The user should be able to select/edit the date time according to his timezone, but since I can only set the ion-datetime value using an ISO-String, which is in zulu time, I have to add the timezone offset, fake it to a zulu string and pass it into the component, after submitting the form i have to manually recalculate the time and pass it to the back end.

In my opinion it is a common practice to have the user select the datetime according to his time zone but still output a ISO-String to pass it to the DB.

Am I missing something or is this just not provided? Why not?

Thank you for any advice…

1 Like

Having the same problem. Does anybody have answer?

Ok, I think I found the solution which doesn’t involve direct offset manipulation.

moment.js plugin allows local time translation to ISO string without changing the time , unlike .toISOString function which always returns GMT time.

Here is code example:

var now = moment();
this.myDate = moment(now.format(), moment.ISO_8601).format();

And in HTML template:

<ion-datetime displayFormat="HH:mm" [(ngModel)]="myDate"></ion-datetime>

Hope it helps.

2 Likes

Nice! One question, how did use the moment.js library? I tried to install their angular2 module but couldn’t figure out how to include it in ionic…

  • For JS you put

    var moment = require('moment');

right after all your imports;

  • For TS:

import * as moment from 'moment';

For more information this is moment.js web site:

http://momentjs.com/

They have pretty good instructions.

Good luck!

3 Likes

Many Thanks You Made my Day :slightly_smiling_face:

1 Like

Glad I could help!:grinning:

It works, thank you so much.