Convert a String to a Single Date in Javascript - 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

Related

how to get number of days from angularjs

how to get number of days between two dates but its not working i think my date format not correct but how to change date format and get number of days
$scope.ChangeDate = function () {
var oneDay = 24 * 60 * 60 * 1000;
var firstDate = $scope.Current.PlainnedStart;
var secondDate = $scope.Current.PlainnedEnd;
if (!angular.isUndefined(firstDate) && !angular.isUndefined(secondDate)) {
var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime()) / (oneDay)));
alert(diffDays);
$scope.Current.NOD = ++diffDays;
}
}
enter image description here
<input type="text" onchange="angular.element(this).scope().ChangeDate()"
id="date" ng-model="Current.PlainnedStart"
class="floating-label mdl-textfield__input" placeholder="">
you can use
<input class="form-control" ng-model="day1" ng-blur="getDate(day1)" type="text" readonly />
$scope.getDate= function (date) {
var dates = new Date();
console.log(dates);
}
you can easily manage with momentjs with date evens
var a = moment('2018-04-17T07:00:00.000Z');
var b = moment('2018-04-27T07:00:00.000Z');
var days = b.diff(a, 'days');
http://momentjs.com/
or with Javascript
var a = new Date("2018-04-17T07:00:00.000Z");
var b = new Date("2018-04-27T07:00:00.000Z");
var dayDif = (a - b) / 1000 / 60 / 60 / 24;
You should convert both dates into the JavaScript Date object. From what I can see, the inputs from both date inputs are in 'dd-mm-yyyy' format, and this will cause some problems if you try to directly convert it into the Date object. Instead, you should convert it to 'yyyy-mm-dd' before converting it to a date object.
Then, you can calculate the difference between both dates.
const str1 = '17-04-2019';
const str2 = '20-04-2019';
const toDate = dateStr => {
const parts = dateStr.split('-');
return new Date(parts[2], parts[1] - 1, parts[0]);
}
const diff = Math.floor((toDate(str2) - toDate(str1) ) / 86400000);
console.log(diff)
As mentioned in the previous answer above you can either split the string to get the values. Or change it like below
Ex:Suppose my date string is
var str1 = '17-Apr-2019';
var str2 = '20-Apr-2019';
var diff = Math.abs(new Date(str2).getDate() - new Date(str1).getDate());
console.log(diff)
Output => 3
Or if you dont want any code changes.
Change the format of the datepicker to (mm-dd-yyyy) you will get same output

Count dates between two HTML Date input fields real time [duplicate]

This question already has answers here:
How to calculate number of days between two dates?
(42 answers)
Closed 6 years ago.
I'm making simple application for record internal leaves of my office. with this application I have to provide users to two HTML date fields for select start leave date and end leave date. At the same time I need to calculate how many days have in between user's selection also this count may exclude the weekdays. To do this i tried to use simple javascript with one of date fields onchange event but it's not working
this is the complete code with HTML I have tried
<html >
<head>
</head>
<body>
<form action='reqprocess.php' method='post'>
<td><input type="date" name="datepicker" class='form-control' id="startd" required/> <br>
<td><input type="date" name="datepicker2" class='form-control' id="endd"required /> <br>
<td><input type="text" name='leavehmd' class='form-control' id="lhmd"/><br>
<input type='submit' value='Apply' class='btn btn-primary' />
</form>
<script type="text/javascript">
var chng1 = document.getElementById("endd");
chng1.onchange = function () {
var date1 = Date.parse(document.getElementById("startd").value);
var date2 = Date.parse(document.getElementById("endd").value);
if (date1 && date2) {
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
//alert(diffDays);
document.getElementById("lhmd").value = diffDays;
}
}
var chng2 = document.getElementById("startd")
chng2.onchange = function () {
var date1 = Date.parse(document.getElementById("startd").value);
var date2 = Date.parse(document.getElementById("endd").value);
if (date1 && date2) {
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
//alert(diffDays);
document.getElementById("lhmd").value = diffDays;
}
}
</script>
</body>
</html>
But when sect second date, on-change function not works and Input field suppose to fill with counted dates not populated. How can I fix this ?
or how can I achieve this via methods like ajax or jquery
You need to make sure there is a value in each input field before attempting to calculate the difference
You can check this by setting a conditional with the values as the operands. They will evaluate to falsy if there is no value and truthy if there is a value. If both values are present, you can then calculate the difference.
The linked duplicate question has a good clean way to count days between dates:
function parseDate(str) {
var mdy = str.split('/');
return new Date(mdy[2], mdy[0]-1, mdy[1]);
}
function daydiff(first, second) {
return Math.round((second-first)/(1000*60*60*24));
}
var chng1 = document.getElementById("endd");
var chng2 = document.getElementById("startd");
chng1.onchange = displayCurrentDayDifference();
chng2.onchange = displayCurrentDayDifference();
function displayCurrentDayDifference() {
var date1 = document.getElementById("startd").value;
var date2 = document.getElementById("endd").value;
if (date1 && date2) {
var daysBetween = daydiff(parseDate($('#startd').val()), parseDate($('#endd').val()));
document.getElementById("lhmd").value = daysBetween;
}
}

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

Javascript simple code error

Can't seem to find the problem. Every time I run it I get NaN for ageDale, been looking at it for a while now, its probably simple but I appreciate the help!
<p>Enter names in the fields, then click "Submit" to submit the form:</p>
<form name="form">
<input type="text" id="birthDate">
Current Date
<input type="text" id="currentDate">
<a id="Submit_Button" onclick="test();" href="javascript:void(0);" title="Submit">Submit</a>
</form>
<script>
function test() {
var birthDate = document.getElementById("birthDate");
var currentDate = document.getElementById("currentDate");
var ageDate = (birthDate.value - currentDate.value);
if(ageDate.value < 1) {
(ageDale = ageDate.value * -1)
}
else {
(ageDale = ageDate.value * 1)
}
alert(ageDale)
}
</script>
Also, is it necessary for me to have that else statement? or is there another way to set up this so its not needed?
This
ageDate.value
should be
ageDate
only. It's a variable and already contains only the difference from
birthDate.value - currentDate.value
if(ageDate.value < 1) {
// ^ here
(ageDale = ageDate.value * -1)
} //^ here
else {
(ageDale = ageDate.value * 1)
// ^ and here
You only need to fetch the value when getting data from, for example, input fields.
Also (depending on how you input them) it might be a problem to calculate dates. For debugging purposes you should
console.log()
your variable values, that way you will find out quickly where the error is.
A good place for a console.log() in your code would be, for example after this block:
var birthDate = document.getElementById("birthDate");
var currentDate = document.getElementById("currentDate");
var ageDate = (birthDate.value - currentDate.value);
console.log(ageDate);
SIDENOTE:
You might want to take a look at moment.js, which will help you with date calculations. For example, you can get differences between dates with moment.js like this:
var a = moment([2014, 12, 05]);
var b = moment([2014, 12, 06]);
a.diff(b, 'days') // 1
Try this:
var btn = document.getElementById("Submit_Button");
btn.onclick = function test() {
var birthDate = parseInt(document.getElementById("birthDate").value);
var currentDate = parseInt(document.getElementById("currentDate").value);
var ageDate = (birthDate - currentDate);
if(ageDate < 1) {
(ageDate = ageDate * -1)
}
else {
(ageDate = ageDate * 1)
}
alert(ageDate)
}
As baao said, you have spelling errors. After correcting those, you want to consider what your input is going to be, and make sure you are checking that the input is valid.
For example, if I type "September 10th" for my birthday and "December 10th" for the current date, your function will try and subtract two strings which is not valid. If you're going to use a custom input field for the date, you need to be sure its in a consistent and parseable format.
I'd recommend asking for just their birthday in a specific format and parsing it from there, since we can use Javascript to get the current date easily. For example, mm-dd-yy. We may re-write it as:
function test() {
//lets get the date, in the format 'mm-dd-yy'. You'd want to do error checking at some point if you're serious about it
var dateInput = document.getElementById("birthDate").value;
//get each individal date type by splitting them at the -, giving ['dd', 'mm', 'yy']
var dateSplit = dateInput.split('-');
//create a Javascript date object with the date we got
var birthDate = new Date(dateSplit[2], dateSplit[0], dateSplit[1]);
//create another with the current date and time
var currentDate = new Date();
// find the difference in milliseconds
var dateDifference = Math.abs(birthDate.getTime() - currentDate.getTime());
// convert to years
var age = dateDifference / (1000 * 3600 * 24 * 365);
alert(age);
}
<p>Enter names in the fields, then click "Submit" to submit the form:</p>
<form name="form">
Birth Date (dd-mm-yy):
<br>
<input type="text" id="birthDate">
<br>
<a id="Submit_Button" onclick="test();" href="javascript:void(0);" title="Submit">Submit</a>
</form>
just modify this code
var birthDate = document.getElementById("birthDate");
var currentDate = document.getElementById("currentDate");
var ageDate = (birthDate.value - currentDate.value);
if(ageDate.value < 1) {
(ageDale = ageDate.value * -1)
}
else {
(ageDale = ageDate.value * 1)
}
with this
var vbirthdate = new Date(document.getElementById("birthDate").value);
var vcurrentdate = new Date(document.getElementById("currentDate").value);
var ageDate = Math.floor((vbirthdate-vcurrentdate)/(1000*60*60*24));
if(ageDate < 1) {
(ageDate = ageDate * -1)
} // no need to do something like this (ageDate *1) if it is already a positive number, just check if it's a negative then convert it to a positive number
you can try the code at http://jsfiddle.net/kapasaja/duco4cqa/5/
what you asking is similar to this post

Categories

Resources