datetime-local different format after selecting - javascript

Given is an ionic app with <input type='datetime-local'> inputs which runs on an android system. The problem ist that the inputs have different formats after the user selects a Dates. Start is after the user selected a date and Ende is the default formatting. I already tried to add the min, max and step attribute.
The format without the miliseconds is the preferred one.
The Controller
$scope.event = {};
// Default dates
$scope.event.start = new Date();
$scope.event.end = new Date();
$scope.event.end.setHours($scope.event.start.getHours() + 2);
The HTML Part
<label class="item item-input underlinedInput equal-padding ">
<span class="input-label">Start</span>
<input type="datetime-local" placeholder="Start" ng-model="event.start" step="1" min="1900-01-01T00:01:00" max="2900-01-01T23:59:59">
</label>
<label class="item item-input underlinedInput equal-padding ">
<span class="input-label">Ende</span>
<input type="datetime-local" placeholder="Ende" ng-model="event.end" step="1" min="1900-01-01T00:01:00" max="2900-01-01T23:59:59">
</label>

For anyone interested, i wrote a factory that solves my problem.
Instead of creating a date like $scope.event.start = new Date() just use $scope.event.start = Tools.currentDate();
.factory('Tools', function () {
return {
utcDate: function (date) {
var d = new Date(date.replace(' ', 'T'));
d.setTime(d.getTime() + d.getTimezoneOffset() * 60 * 1000);
return d;
},
currentDate: function () {
var d = new Date();
var year = d.getFullYear();
var month = this.leadingZero(d.getMonth());
var day = this.leadingZero(d.getDate());
var hour = this.leadingZero(d.getHours());
var minutes = this.leadingZero(d.getMinutes());
return this.utcDate(year+"-"+month+"-"+day+"T"+hour+":"+minutes+":00");
},
leadingZero: function(number){
return ("0"+number).substr(-2,2);
}
}
})

use date object like
$scope.event.start = new Date(2010, 11, 28, 14, 57);
refer this plunker

you can use moment JS and you will have a better control over date manipulation in your app. moment js docs
var startDate = moment().format('DD/MM/YYYY, HH:MM A');
var endDate = moment().add(2, 'hours').format('DD/MM/YYYY, HH:MM A')

Related

How to restrict date range for 15 days only

I want to restrict date for fifteen days only, I have written some code but don't know where I am going wrong. If anyone can guide me it would be helpful.
this is my full code, I am applying condition also to check if date is greater then 15 but it's not working
<body>
<form>
<div class="container">
<h4>Start Date:</h4>
<input type="text" id="startdate" name="fromdate" width="276"
placeholder="dd/mm/yyyy" required onchange="checkDate()" />
<h4>End Date:</h4>
<input type="text" id="enddate" name="todate" width="276"
placeholder="dd/mm/yyyy" required onchange="checkDate()"/>
</div>
<input type="submit" value="submit">
</form>
<script>
var today = new Date(new Date().getFullYear(), new Date().getMonth(),
new Date().getDate());
$('#startdate').datepicker({
uiLibrary : 'bootstrap4',
iconsLibrary : 'fontawesome',
format : 'dd/mm/yyyy',
maxDate : function() {
return $('#enddate').val();
}
});
$('#enddate').datepicker({
uiLibrary : 'bootstrap4',
iconsLibrary : 'fontawesome',
format : 'dd/mm/yyyy',
minDate : function() {
return $('#startdate').val();
}
});
//function to check wether date is more than 15 its not workin
//all plugins are there u just have to run
function checkDate(){
var start = $('#startdate').val();
var end = $('#enddate').val();
//convert strings to date for comparing
var startDate = new Date(start);
var endDate = new Date(end);
// Calculate the day diffrence
var oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
var diffDays = Math.abs((endDate.getTime() - startDate.getTime()) / (oneDay));
if(diffDays > 15){
alert("Days are more then fifteen");
}
}
</script>
</body>
</html>
here is the fiddle
It's because your datepicker has format dd/mm/yyyy but Date constructor converts it as if it was mm/dd/yyyy.
var date = '01/03/2018'
var d = new Date(date);
console.log(d.toString())
You need to adapt your code to work with dd/mm/yyyy format
function checkDate(start, end){
//convert strings to date for comparing
var startDate = createDate(start);
var endDate = createDate(end);
// Calculate the day diffrence
var oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
var diffDays = Math.abs((endDate.getTime() - startDate.getTime()) / (oneDay));
if(diffDays > 15){
console.log("Days are more then fifteen");
} else {
console.log("Less than 15 days")
}
}
function createDate(datestr){
var datearr = datestr.split("/");
var d = new Date(datearr[2], Number(datearr[1]) - 1, datearr[0])
return d;
}
checkDate("01/02/2018", "10/02/2018")
checkDate("01/02/2018", "30/02/2018")
jsfiddle
The issue is with the date format you're using. 'dd/mm/yyyy' is not a format Date.parse() can handle.
String value representing a date. The string should be in a format
recognized by the Date.parse() method
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#Parameters
So you can either change the format to 'mm/dd/yyyy' or you can use moment.js to handle your date manipulations.
If you prefer to stick with the same format and Date library, then you have a solution here
PS: I noticed you have asked the same question before and having issues with the accepted answer. When this happens, please comment on the answer instead of making a duplicate
Look at this answer, here I have used a moment.js library also. this will restrict to 15 days. Hope this sample will give you a solution
$(document).ready(function(){
$('#date-of-ending').datepicker({
autoclose: true,
format:"dd/mm/yyyy"
})
$('#date-of-starting').datepicker({
autoclose: true,
format:"dd/mm/yyyy"
}).on('changeDate', function (selected) {
var xDays = 15;
var selectedDate = moment(selected.date,"DD/MM/YYYY").format("MM/DD/YYYY")
var maxDate = moment(selectedDate.valueOf()).add(xDays, 'days').format('DD/MM/YYYY'); // This is from moment js library
$('#date-of-ending').datepicker('setEndDate', maxDate);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.8.0/js/bootstrap-datepicker.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.8.0/css/bootstrap-datepicker.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
<input id="date-of-starting" type="text" name="startDate" value="" readonly class="form-control" required />
<input id="date-of-ending" type="text" name="endDate" value="" readonly class="form-control" required />

How can I calculate the 2 datetime picker?

I have 2 datetimepickers and I want to know to calculate the day or time.
Ex:
2017-01-12 09:00:00
2017-01-12 10:00:00
The answer should be 1:00:00
Below is my code. I also wanna know the date time formatting for this.
<input required type="text" class="form-control" id="time_in">
<input required type="text" class="form-control" id="time_out">
$start_time = $("#time_in").val();
$end_time = $("#time_out").val();
$answer = date_diff($start_time, $end_time)
alert($start_time);
This will do what you want to achieve.
Try:
old_date = "2010-11-10 07:00:00";
new_date = "2010-11-10 08:00:00";
old_date_obj = new Date(Date.parse(old_date, "dd/mm/yyyy HH:mm:ss"));
new_date_obj = new Date(Date.parse(new_date, "dd/mm/yyyy HH:mm:ss"))
t = (new_date_obj - old_date_obj);
seconds=(t/1000)%60
minutes=(t/(1000*60))%60
hours=(t/(1000*60*60))%24
alert(hours+":"+minutes+":"+seconds)
probably want something like
function date_diff(start, end)
{
var d1 = new Date(start);
var d2 = new Date(end);
return d2-d1;
}
note that the answer here is in miliseconds
var date;
date = new Date("$start_time);
var startTime = date.getTime();
date = new Date("$end_time);
var endTime = date.getTime();
var difference=startTime-endTime;
var answer= new Date(difference);
Hope this Helps.

Calculate all dates in between given start and end date using javascript

I have a start-date and end-date and I want to calculate array of dates between these days based on a given duration.
for example,
if start date is 01/01/2015 and end date is 01/06/2015 and if I give duration as 3 months then out put should be:
01/04/2015
01/06/2015
How to achieve this using JavaScript and I need to display it in a form.
If you want to calculate difference between two dates using javascript:
Then,
function dateDiff() {
var dtFrom = document.getElementById('txtFromDate').value;
var dtTo = document.getElementById('txtToDate').value;
var dt1 = new Date(dtFrom);
var dt2 = new Date(dtTo);
var diff = dt2.getTime() - dt1.getTime();
var days = diff/(1000 * 60 * 60 * 24);
alert(dt1 + ", " + dt2);
alert(days);
return false;
}
function isNumeric(val) {
var ret = parseInt(val);
}
HTML:
<label for="txtFromDate">From Date : </label>
<input type="text" id="txtFromDate" name="txtFromDate" size="10" maxlength="10" value="03/25/2013"/><br/>
<label for="txtToDate">To Date : </label>
<input type="text" id="txtToDate" name="txtDate" size="10" maxlength="10" value="03/26/2013"/><br/>
<button id="btnCheck" name="btnCheck" onClick="dateDiff();" type="button">Difference</button>
AFTER EDIT:
Following solution is to get all dates between specified dates.
Working Demo
// using Datepicker value example code
$('#getBetween').on('click', function () {
var start = $("#from").datepicker("getDate"),
end = $("#to").datepicker("getDate");
var between = getDates(start, end);
$('#results').html(between.join('<br> '));
});
// This function doing this work.
function getDates(start, end) {
var datesArray = [];
var startDate = new Date(start);
while (startDate <= end) {
datesArray.push(new Date(startDate));
startDate.setDate(startDate.getDate() + 1);
}
return datesArray;
}

Javascript: Subtract time with another fixed time

Consider I have following date and time in 24 hours format.
Example
2015/04/02 12:00
2015/03/02 14:00
I have to subtract the above time with 9 hours so that I will get
2015/04/02 -> 3 (hours)
2015/03/02 -> 5 (hours)
HTML
<form name="formName" onsubmit="return checkDate(this)">
<input type="text" value="" name="date1" />
<input type="text" value="" name="date2"/>
<input type="submit" value="Submit">
</form>
<p id="demo"></p>
Javascript
function checkDate(theForm)
{
var a = theForm.date1.value;
var b = theForm.date2.value;
var date1 = new Date(a);
var date2 = new Date(b);
var dateStart = new Date();
var dateEnd = new Date();
dateStart.setHours(9);
Start_sec = (date1/ 1000.0) - (dateStart/ 1000.0);
Start_hours = parseInt(Start_sec / 60 / 60);
document.getElementById("demo").innerHTML = Start_hours ;
return false;
}
Try the following code.
function checkDate(theForm)
{
var a = theForm.date1.value;
var b = theForm.date2.value;
var date1 = new Date(a);
var date2 = new Date(b);
date1.setHours(date1.getHours() - 9);
date2.setHours(date2.getHours() - 9);
document.getElementById("demo").innerHTML = "Date 1 : " + date1.toString() + "<br/>Date 2 : " + date2.toString();
return false;
}
If it is acceptable to use third party libraries, then you can achieve this task simply using moment.js. In one line, you can accomplish the task with this code:
moment('2015/04/02 12:00').subtract('hours',9).format('YYYY/MM/DD hh:mm')
//just a number plus the word 'hours'
.format('h [hours]')
//time only
.format('h:mm')
Occasionally I update this fiddle I maintain with more examples: http://jsfiddle.net/JamesWClark/9PAFg/
var date = new Date("2015/04/02 12:00");
var out = new Date(date.getTime() - 32400000); //9*60*60*1000
You can just literally subtract 9 hours directly...:
var t = new Date(2015,2,3,18);
t.setTime(t - 9*60*60*1000); //subtract 9 hours

Convert a String to a Single Date in Javascript

I have an input text that has a combination of date and time and display like this
04/01/2015 8:48PM
How can i convert this string to a date using the function new Date() in javascript? not output is shown
Here is what i've tried so far, i can only convert the date not the time.
HTML
<form name="frm1" >
<h3>Check in Date:</h3>
<input type="text" value="" class="datetimepicker_mask" name="dtp1" /><br><br>
<h3>Check out Date:</h3>
<input type="text" value="" class="datetimepicker_mask" name="dtp2" /><br><br>
<input type="button" onclick="computeDate()" value="Compute Difference" />
<br><b>No of days: </b>
<span id="date_difference"></span>
</form>
JAVSCRIPT
function computeDate() {
var dateTime1 = document.frm1.dtp1.value;
var dateTime2 = document.frm1.dtp2.value;
var startDate = new Date(dateTime1);
var endDate = new Date(dateTime2);
var timeDiff = Math.abs(endDate.getTime() - startDate.getTime());
if (timeDiff == 0) {
timeDiff = 1;
}
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
var total = parseFloat(diffDays) * parseFloat(roomRate);
document.getElementById("date_difference").innerHTML = diffDays;
document.getElementById("date_difference").style.visibility = "visible";
}
If the date format is always the same, create a convience function that converts the date to a Date object
function convert(date) {
var dateArr = date.split(/[\s\/\:]/);
if (dateArr[4].toLowerCase().indexOf('pm') != -1)
dateArr[3] = (+dateArr[3]) + 12;
dateArr[4] = dateArr[4].replace(/\D/g,'');
dateArr[0]--;
return new Date(dateArr[2], dateArr[0], dateArr[1], dateArr[3], dateArr[4]);
}
FIDDLE
Here is an answer that will both solve this and make development easier. This suggestion will require an extra library for addressing such issues as you are having here- time, but you'll likely find it beneficial when working with JavaScript dates in general. It already looks like you're writing manual date functions. Abstract them away with robust libraries for solving these same issues that have come up again and again. Using date.js, here is how easy this becomes
Date.parse('04/01/2015 8:48PM ')
JSFiddle Example
You can create the Date object after parsing the dateString
var d = new Date(year, month, day, hours, minutes, seconds, milliseconds);
you can use the parseDate function as following
var testDate = "04/01/2015 8:48PM";
console.log(parseDate(testDate));
function parseDate(dateStr){
var dateTime = dateStr.split(/\/| |:|(?=[PA])/);
for(var i=0; i<5; i++){
dateTime[i] = parseInt(dateTime[i]);
}
if(dateTime[5] == "PM"){
dateTime[3] += 12;
}
return new Date(dateTime[2], dateTime[1], dateTime[0], dateTime[3], dateTime[4]);
}
Try it at JSFiddle

Categories

Resources