How to execute strftime in javascript ? - javascript

I am making a countdown counter where the user is entering the start date and duration and then the End date gets calculated. And based on this End date a countdown counter starts.
But the issue here is that the counter is giving the wrong output. The number of months, days, hours, min, sec everything is fine except the year.
I think there is something wrong with my srftime command.
<script src="external/jquery/dateFormat.min.js" type="text/javascript"></script>
<script src="external/jquery/jquery.countdown.min.js" type="text/javascript"></script>
<script src="jquery-ui.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#start_date").datepicker({ minDate: 0 });
$("#setCounter").on("click",function(){
var startDate = $("#start_date").val();
var duration = $("#period").val();
if (startDate == "" || duration == "") {
alert("Please fill all the fields.");
return;
}
stopDate = new Date(startDate);
stopDate.setMonth(stopDate.getMonth() + parseInt(duration));
stopDate = DateFormat.format.date(stopDate,"MM/dd/yyyy");
$("#end_date label").html(stopDate);
$("#end_date").show();
var today = DateFormat.format.date(new Date(),"MM/dd/yyyy");
todayObj = new Date(today);
startDateObj = new Date(startDate);
todayTimestamp = Date.UTC(todayObj.getFullYear(),todayObj.getMonth(), todayObj.getDate());
startDateTimestamp = Date.UTC(startDateObj.getFullYear(),startDateObj.getMonth(), startDateObj.getDate());
if (todayTimestamp >= startDateTimestamp) {
$('#getting-started').countdown(stopDate, function(event) {
$(this).html(event.strftime('%Y year %m month %d days %H:%M:%S'));
});
};
});
});
</script>
My html code is as follows:
<div>
<p>Start Date: <input type="text" id="start_date"></p>
<p>Period: <input type="text" id="period" placeholder="No. of Months"></p>
<p id="end_date">End Date: <label></label></p>
<p><input type="button" value="Add Counter" id="setCounter" /></p>
</div>
<div id="getting-started"></div>

Related

Returning Value from JavaScript Function into HTML Form Input Value Attribute

I am trying to auto fill a form element with the current date and time in a specific format required by mySQL. My difficulty is auto-filling this value into a form element. So far I have tried using .getElementById("element_id").innherHTML = timestamp
But this does not result in any text filling the form element:
<html>
<head>
<title>Create New Reservation</title>
<script>
function Timestamp()
{
const currentTime = new Date();
var year = currentTime.getFullYear();
var month = currentTime.getMonth();
var day = currentTime.getDate();
var dash = "-";
var space = " ";
var colon = ":";
var hour = currentTime.getHours();
var minutes = currentTime.getMinutes();
var seconds = currentTime.getSeconds();
var timestamp = year.toString().concat(dash, month, dash, day, space, hour, colon, minutes, colon, seconds);
document.getElementById("occurred").innerHTML = timestamp;
}
</script>
</head>
<body onload="Timestamp()">
<h1>Enter Reservation Details</h1>
<form method="POST" action="reservation_process.php">
<fieldset>
<label>Current Time</label><type="text"/>
<input type="text" id="occurred" name="occurred"
<br>
<input type="submit" name="Process" value="Create Entry" />
</form>
</body>
</html>
I have also tried returning the formatted timestamp from the function directly into the value="" attribute, but I suspect my syntax is incorrect and I have not been able to find any HTML documentation on how to do this properly:
<input type="text" id="occurred" name="occurred" value= Timestamp() >
You can use $('#occurred').val(timestamp); instead of document.getElementById("occurred").innerHTML = timestamp; inside your function.
$(element).val(value) sets the value of an input, if you not already have you need to include jQuery to use this.
function Timestamp(){
const currentTime = new Date();
var year = currentTime.getFullYear();
var month = currentTime.getMonth();
var day = currentTime.getDate();
var dash = "-";
var space = " ";
var colon = ":";
var hour = currentTime.getHours();
var minutes = currentTime.getMinutes();
var seconds = currentTime.getSeconds();
var timestamp = year.toString().concat(dash, month, dash, day, space, hour, colon, minutes, colon, seconds);
$('#occurred').val(timestamp);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<head>
<title>Create New Reservation</title>
<script>
</script>
</head>
<body onload="Timestamp()">
<h1>Enter Reservation Details</h1>
<form method="POST" action="reservation_process.php">
<fieldset>
<label>Current Time</label><type="text"/>
<input type="text" id="occurred" name="occurred"
<br>
<input type="submit" name="Process" value="Create Entry" />
</form>
</body>
</html>

Get date from datepicker not working as expected

I am trying to show an alert when someone selects a date in the past:
jQuery('#date').datepicker().change(evt => {
var selectedDate = jQuery('#date').datepicker('getDate');
var theSelectedDate = selectedDate.setHours(0,0,0,0);
var now = new Date();
var theNow = now.setHours(0,0,0,0);
if (theSelectedDate > theNow) {
// Date in in the future, all good
} else {
alert("Selected date is in the past");
}
});
..and the date field...
<input type="date" id="date" name="date" />
The problem is that regardless of what date I chose with the date picker, the alert is always 'Selected date is in the past' on mobile devices.
What the heck am I doing wrong?
I am not sure why you do not set the Min Date so that Users cannot select a past date.
$(function() {
$("#date").datepicker({
minDate: "+1d"
});
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<p>Date: <input type="text" id="date"></p>
You can use 0 for today or +1d to exclude today.
Update
For Native HTML5 datepicker, you can leverage the min attribute.
You can use the min and max attributes to restrict the dates that can be chosen by the user.
$(function() {
function nowStr() {
var dt = new Date();
var yy = dt.getFullYear();
var m = (dt.getMonth() + 1);
m = m < 10 ? "0" + m : m;
var d = dt.getDate();
d = d < 10 ? "0" + d : d;
var s = yy + "-" + m + "-" + d;
return s;
}
$("#date").attr("min", nowStr());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="date" id="date" name="date" min="2019-01-01" />
Try this.
I have shifted now above the selected date
jQuery('#date').datepicker().change(evt => {
var now = new Date();
var selectedDate = jQuery('#date').datepicker('getDate');
var theSelectedDate = selectedDate.setHours(0,0,0,0);
var theNow = now.setHours(0,0,0,0);
if (theSelectedDate >= theNow) {
alert("Selected date is correct !!!!!!!");
// Date in in the future, all good
} else {
alert("Selected date is in the past");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"/>
<input type="text" class="form-control" id="date" name="date" placeholder="DD/MM/YYY">
Your looking for the onSelect event:
$("#date").datepicker({
onSelect: function(dateText, inst) {
var selectedDate = new Date(dateText);
var theSelectedDate = selectedDate.setHours(0,0,0,0);
var now = new Date();
var theNow = now.setHours(0,0,0,0);
if (theSelectedDate > theNow) {
console.log(true);
// Date in in the future, all good
} else {
console.log(false);
alert("Selected date is in the past");
}
}
});
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js" type="text/javascript"></script>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="Stylesheet" type="text/css" />
<input type="date" id="date" name="date" />
See this answer

How to separate regex in javascript Hours format

I have some problem to define hours time, i want to separate hours time to 3 time type morning, evening, and night.
if time start from 00:00 to 10:00 the type time is morning,
if time start from 10:01 to 18:00 the type time is evening,
if time start from 18:01 to 23:59 the type time is night,
i have code jquery like this
$(document).ready(function(){
$('#submit').on('click',function(){
var hrs=$('#hours').val();
var nm=$('#scedule').val();
var patt = new RegExp("^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$");
var patts = patt.test(hrs);
//morning = 00:00 - 10:00
var morn = new RegExp("^([0-9]|0[0-9]|1[0-9]):[0-5][0-9]$");
var morning = morn.test(hrs);
//evening = 10:01 - 18:00
var even = new RegExp("^(1[0-9]|[0-9]):[0-5][0-9]$");
var evening = even.test(hrs);
//night = 18:01 - 00:00
var nig = new RegExp("^(1[0-9]|2[0-3]):[0-5][0-9]$");
var night = nig.test(hrs);
if ( patts == morning ) {
alert('This is Morning');
} else if (patts == evening){
alert('This is Evening');
} else if (patts == night){
alert('This is night');
} else {
alert('Format is wrong');
}
});
});
and this is my form HTML :
Scedule : <input type="text" id="scedule"><br>
Time : <input type="text" id="hours"><br>
<input type="submit" value="submit" id="submit"><br>
You don't need a regex here, just use Date:
$(document).ready(function(){
$('#submit').on('click',function(){
var hrs=$('#hours').val();
if(hrs.length != 5 || hrs.indexOf(':') < 0)
{
alert("Wrong Fromat")
return;
}
var date = new Date();
date.setHours(hrs.split(":")[0]);
date.setMinutes(hrs.split(":")[1]);
console.log(date)
if ( date.getHours() < 10) {
console.log('This is Morning');
} else if (date.getHours() > 18 && date.getMinutes > 0){
console.log('This is night');
} else{
console.log('This is Evening');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
Time : <input type="text" id="hours"><br>
<input type="submit" value="submit" id="submit"><br>

Set custom time on bootstrap TimePicker

i have 2 time pickers in my page like
<div class="form-group">
<input class="time ui-timepicker-input" id="FromTime" name="FromTime" type="text" value="" autocomplete="off">
</div>
<div class="form-group">
<input class="time ui-timepicker-input" id="ToTime" name="FromTime" type="text" value="" autocomplete="off">
</div>
$(document).ready(function () {
$('#ToTime').timepicker();
$('#FromTime').timepicker();
});
Now i want to set ToTime = FromTime + 1 hour
To raise FromTime value change event and i use the code
$('#FromTime').timepicker().on('changeTime.timepicker', function(e) {
//how to get selected time here
//set ToTime value with a difference of 1 hour ie if 12:30 am selected set ToTime as 1:30 am
});
Try this code
Demo
JS
$(document).ready(function () {
$('#FromTime').timepicker({
defaultTime: false
});
});
var HoursToAdd = 2;
$('#FromTime').timepicker().on('changeTime.timepicker', function (e) {
var meridian = e.time.meridian
var hours = e.time.hours
var minutes = e.time.minutes
var seconds = e.time.seconds
var NewTime;
if (meridian == 'AM') {
NewTime = new Date('', '', '', hours, minutes, seconds)
} else if (meridian == 'PM') {
NewTime = new Date('', '', '', (hours + 12), minutes, seconds)
}
NewTime.setHours(NewTime.getHours() + HoursToAdd)
$('#ToTime').timepicker({
defaultTime: NewTime.getHours() + " : " + NewTime.getMinutes()
});
});

Javascript Calculate Age from HTML input date type

I am trying to calculate age using Javascript. The choose their date of birth from an HTML date input type and his/her age should be displayed. How can Javascript use the HTML Date input type data and calculate age?
Below is the HTML
<html>
<head>
<title> Sample Date of Birth Registration</title>
<script type="text/javascript" src="formiteration6.js"></script>
</head>
<body>
<h1>Birth Registration</h1>
<hr />
<form id ="inputFrom">
<label for="size_1">D.O.B:</label><input type="date" name="size" id="birthDate" value="dd/mm/yy" />
<input type='button' onclick='regBirth()' value='Add new person' />
</form>
<hr />
<table id="details">
<tr>
<th>Date of Birth</th>
<th>Age</th>
</tr>
</table>
<h4>Statistics</h1>
<hr />
<h5><b>Total Count:</b></h5>
<p id="count"></p>
</body>
</html>
And Javascript is here
var allPeople = [];
function regBirth() {
'use strict';
var myArray = {};
var actualDob = myArray.actualBirthDate;
actualDob = document.getElementById('birthDate').value
allPeople.push(myArray);
var inputForm = document.getElementById("inputFrom").reset();
var tabularForm = document.createDocumentFragment();
var tablerow = document.createElement('tr');
var dob = document.createElement('td');
dob.innerHTML = actualDob;
tablerow.appendChild(dob);
tabularForm.appendChild(tablerow);
document.getElementById("details").appendChild(tabularForm);
var totalPeople = allPeople.length;
document.getElementById("count").innerHTML=totalPeople;
}
Get Today's Date using new Date()
Get Date of Birth using new Date(datestring)
Get Year from both Dates using getFullYear()
Now find the Difference between two Years.
Fiddle Demo
in js
// Make a button that display the current date and time in local format on the page.
function mydateis(){
const d = new Date();
let text = d.toLocaleString();
document.getElementById("date").innerHTML = text;
var year_born = prompt("Please enter your date of birth:", 1998);
var month_born = prompt("Please enter your month:", 1);
var month_day = prompt("Please enter your day:", 1);
function getAge(birthYear,month_born,month_day){
var currentDate = new Date();
var currentYear = currentDate.getFullYear();
var currentmonth = currentDate.getMonth();
var currentday = currentDate.getDate();
console.log(currentDate);
console.log(currentDate.getDate());
age = currentYear - birthYear;
month = currentmonth - month_born;
day = currentday - month_day;
return age,month,day;
}
calculatedAge = getAge(year_born,month_born,month_day);
document.getElementById("yearsold").innerHTML ="you have yeyre is" + age+ " and "+month+" month and days is "+day ;
}
in html
<button onclick="mydateis()">date is </button>
<h4>hekoo date is </h4>
<p id="date"></p>
<p id="yearsold"></p>
the out bot is

Categories

Resources