Isuru Avishka
Isuru Avishka

Reputation: 43

How to combine date and time into a single datetime object?

In my react native app i need to combine my date and time in to single datetime object. I used react native modal date time picker npm package for get date and time.

I have a datepicker returning a date string, and a timepicker returning a time string. When i try to combine it will give me a output as Invalid date.

concatDateTime = () => {

    var date = this.state.date;
    var time = this.state.currentTime;

    var dateTime = Moment(date + ' ' + time, 'DD/MM/YYYY HH:mm');

    console.log(dateTime.format('YYYY-MM-DD HH:mm'));
}

I need dateobject in ('YYYY-MM-DDTHH:mm:s') format.

Upvotes: 3

Views: 12053

Answers (3)

300baud
300baud

Reputation: 560

Another alternative:

let mDate = moment(data.StartDateLocal).tz("Australia/Melbourne");
let mTime = moment(data.StartTimeLocal).tz("Australia/Melbourne");
let x1 = {
    'hour':    mTime.get('hour'),
    'minute':  mTime.get('minute'),
    'second':  mTime.get('second')
}                
mDate.set(x1);
this._json.header.transactionStartDateTime = mDate.format("YYYY-MM-DDTHH:mm:ss");

Upvotes: 0

Sagar Kulthe
Sagar Kulthe

Reputation: 848

Just click on below link, https://stackblitz.com/edit/typescript-bmgx2p?file=index.ts

I hope it will solve your problem.

Upvotes: 0

Ray Chan
Ray Chan

Reputation: 1180

You can specify the format of your input string to let moment know how to parse it.

var date = '2019-02-16';
var time = '8:24 PM';

// tell moment how to parse the input string
var momentObj = moment(date + time, 'YYYY-MM-DDLT');

// conversion
var dateTime = momentObj.format('YYYY-MM-DDTHH:mm:s');

console.log(dateTime);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>

Upvotes: 9

Related Questions