6

I have two input tags for picking date and time from user.

<p>Start Date</p><p> <input ng-model="sdate" type="date" ></p>
<p>Start Time</p><p> <input ng-model="stime" type="time" ></p>

These two values are passed to a function where I want to combine these two input values as a Date object:

 new Date(y, m, d, hh, mm, a)

Which I can then use to plot an event's details in a Calendar. How can I combine these two values? I have tried:

start:new Date(sdate + stime)


start:new Date(sdate , stime)


start: new Date(sdate.getFullYear() + sdate.getMonth() + sdate.getDate() + stime.getHours + stime.getMinutes())

But none of what I have tried is working.

How do I achieve this when using AngularJS?

1
  • 1
    Doesn't Angular just create native HTML5 date inputs in supporting browsers, and what would the returned value from those be in different browsers ? Commented Feb 4, 2014 at 12:57

6 Answers 6

7

In angular it would go something like this:

Controller:

function exampleController($scope) {
    $scope.title = "$Watch sample";   

    $scope.$watch('sdate', function() {
       tryCombineDateTime(); 
    });

    $scope.$watch('stime', function() {
       tryCombineDateTime();
    });

    function tryCombineDateTime() {
        if($scope.sdate && $scope.stime) {
            var dateParts = $scope.sdate.split('-');
            var timeParts = $scope.stime.split(':');

            if(dateParts && timeParts) {
                dateParts[1] -= 1;
                $scope.fullDate = new Date(Date.UTC.apply(undefined,dateParts.concat(timeParts))).toISOString();
            }
        }
    }
}

HTML

<div ng-app ng-controller="exampleController">
    <h2>{{title}}</h2>
    <p>Start Date</p><p> <input ng-model="sdate" type="date" ></p>
    <p>Start Time</p><p> <input ng-model="stime" type="time" ></p>

    {{fullDate}}
</div>

You need to make use of the $watch listener on a variable when it changes, then call your function.

Note: it would be even better if you make a directive for this.

Fidle

Sign up to request clarification or add additional context in comments.

2 Comments

Don't forget that the month is zero referenced when using Date and so you will need to subtract 1 or the month will be incorrect.
Not working, getting an error that split is not a function
3

A very naive approach to combine these two is to split date-components and time-components and make a string. Then make a new Date object using this string.

Input is taken from here:

<p>Start Date</p><p> <input ng-model="sdate" type="date" ></p>
<p>Start Time</p><p> <input ng-model="stime" type="time" ></p>

Then in script part, split date and time components as follows:

        var dd = new Date(sdate).getDate();
        var mm = new Date(sdate).getMonth()+1;
        var yy = new Date(sdate).getFullYear();
        var hh = new Date(stime).getHours();
        var ms = new Date(stime).getMinutes();

Then Combine these components to form a string as required(in Calendar):

var x = yy + ',' + mm + ',' + dd + ' ' + hh + ':' + ms;

Now create a new Date object:

var finaldate = new Date(x);

3 Comments

This would assume that the environment's Date constructor parses the strings correctly, which is often not the case. Otherwise you could just shorten this to new Date(sdate + ' ' + stime) and forgo the multiple parsing that you are performing.
Actually, I tried your method initially, but it wasn't working. Also can you provide details about in which case parsing won't work correctly?
This is problem, parsing a datetime string in Javascript using Date is unreliable. Search here on SO and on Google and you will find links to tabulated results.
1

You could do something like this, though this doesn't have anything to do with AngularJS and I can't test on older browsers. I am assuming that you are entering date/time as UTC and I am using Date to create an ISO8601 timestamp as an output. Also assumes that you are using a modern browser that supports HTML5 and ECMA5, otherwise you will need to modify the code.

HTML

<p>Start Date</p><p> <input id="myDate" ng-model="sdate" type="date" ></p>
<p>Start Time</p><p> <input id="myTime" ng-model="stime" type="time" ></p>
<div id="myIso"></div>

Javasceipt

var myIso = document.getElementById('myIso'),
    dateParts,
    timeParts;

function joinPartsAsDate() {
    if (dateParts && dateParts.length === 3 && timeParts && timeParts.length === 2) {
        // dateParts[1] -= 1; could be done here
        myIso.textContent = new Date(Date.UTC.apply(undefined, dateParts.concat(timeParts))).toISOString();
    } else {
        myIso.textContent = '';
    }
}

document.getElementById('myDate').addEventListener('change', function (e) {
    dateParts = e.target.value.split('-');
    if (dateParts[1]) { // this could be done in joinPartsAsDate, here for clarity
        dateParts[1] -= 1;
    }

    joinPartsAsDate();
}, false);

document.getElementById('myTime').addEventListener('change', function (e) {
    timeParts = e.target.value.split(':');
    joinPartsAsDate();
}, false);

On jsFiddle

Comments

1

After testing all stuff described here, i found a very simple solution. In my view i have

<input type="date" ng-model="tsc.untilDate">
<input type="time" ng-model="tsc.untilTime">

In my Angular Controller both model elements are objects from type Date by default. With input type="date" the time of this Date object is always 00:00. With input type="time" the date part of the Date object ist allways set to today. So i just read the daytime (if it is set) of the TimeDate Object and set it on the DateObject.

if(tsc.untilTime)
{
  tsc.untilDate.setHours(tsc.untilTime.getHours());
  tsc.untilDate.setMinutes(tsc.untilTime.getMinutes());
}

1 Comment

This was really the easiest option. Not sure why the other options are higher voted
0

For those looking for a compact version install the momentjs library.

npm install moment --save 

Add it to your file header.

import * as moment from 'moment';

Then just compose the dateTime object with the fluent interface.

let dateTime = moment(this.sdate)
    .startOf('day')
    .set('hour', this.sTime.getHours())
    .set('minute', this.sTime.getMinutes() )
    .toDate();

Comments

0

Try this

const timeAndDate = moment(this.sdate + ' ' + this.sTime.getHours() + ' '  +  this.sTime.getMinutes());

console.log(timeAndDate.toDate());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.