Changing a ISO date to a Short date JavaScript - javascript

I currently have a function setup to get the following two weeks or months from the selected date from a input date field. However, the problem I'm facing is that I want to get the date to output DD/MM/YYYY but I'm getting the full ISO date where I need the short. Does anyone know how I can go about doing this?
EDIT:
I've added the moment(date1).format('DD/MM/YYYY'); to test the code but this hasn't provided any results.
function submit() {
var type = document.getElementById("selectType").value;
var dateSelected = document.getElementById('datePicker').valueAsDate = new Date();
if (type === "Months") {
document.getElementById("pWeeks").className = "hidden";
document.getElementById("pMonths").className = "";
var date1 = dateSelected;
moment(date1).format('DD/MM/YYYY');
var date2 = new Date(date1);
date2.setMonth(date2.getMonth() + 1);
document.getElementById("pM1").innerHTML = date1;
document.getElementById("pM2").innerHTML = date2;
} else {
document.getElementById("pWeeks").className = "";
document.getElementById("pMonths").className = "hidden";
var date1 = dateSelected;
var date2 = new Date(date1);
date2.setDate(date2.getDate() + 7);
document.getElementById("pW1").innerHTML = date1;
document.getElementById("pW2").innerHTML = date2;
}
}
.hidden {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<input type="date" id="datePicker"><br>
<select id="selectType">
<option value="Months">Months</option>
<option value="Weeks">Weeks</option>
</select><br>
<button id="submit" onclick="submit()">Submit</button>
<div id="pMonths" class="">
<p id="pM1"></p>
<p id="pM2"></p>
</div>
<div id="pWeeks" class="">
<p id="pW1"></p>
<p id="pW2"></p>
</div>

First off, you are setting the input value to the current date right here
var dateSelected = document.getElementById('datePicker').valueAsDate = new Date();
don't do that, it kind of defeats the purpose of having a selector in the first place.
As for converting the Dates, I would use Date.prototype.toLocaleDateString() passing "en-US" as the locale:
console.log((new Date()).toLocaleDateString('en-US')); // format MM/DD/YYY
I also fixed how you set the new dates, it now takes one date and adds either one and two months or one and to weeks instead of none and one month and none and one week ;-)
function submit() {
var type = document.getElementById("selectType").value;
var dateSelected = document.getElementById('datePicker').valueAsDate;
if (type === "Months") {
document.getElementById("pWeeks").className = "hidden";
document.getElementById("pMonths").className = "";
var date1 = dateSelected;
var datePlusOne = new Date(date1);
datePlusOne.setMonth(date1.getMonth() + 1);
var datePlusTwo = new Date(date1);
datePlusTwo.setMonth(date1.getMonth() + 2);
document.getElementById("pM1").innerHTML = datePlusOne.toLocaleDateString('en-US');
document.getElementById("pM2").innerHTML = datePlusTwo.toLocaleDateString('en-US');
} else {
document.getElementById("pWeeks").className = "";
document.getElementById("pMonths").className = "hidden";
var date1 = dateSelected;
var datePlusOne = new Date(date1);
datePlusOne.setDate(date1.getDate() + 7);
var datePlusTwo = new Date(date1);
datePlusTwo.setDate(date1.getDate() + 14);
document.getElementById("pW1").innerHTML = datePlusOne.toLocaleDateString('en-US');
document.getElementById("pW2").innerHTML = datePlusTwo.toLocaleDateString('en-US');
}
}
.hidden {
display: none;
}
<input type="date" id="datePicker"><br>
<select id="selectType">
<option value="Months">Months</option>
<option value="Weeks">Weeks</option>
</select><br>
<button id="submit" onclick="submit()">Submit</button>
<div id="pMonths" class="">
<p id="pM1"></p>
<p id="pM2"></p>
</div>
<div id="pWeeks" class="">
<p id="pW1"></p>
<p id="pW2"></p>
</div>

Instead of document.getElementById("pM1").innerHTML = date1; you should build first a string with the methods provided by the date object ( getFullYear, getDate, getMonth; see docu ). Then you can assign the string to the innerHtml.
If you can use the moment.js then your code which you assign to your innerHtml is date1 = moment(dateSelected).format('DD/MM/YYYY')
Also I would recommend Luca's way:
As for converting the Dates, I would use Date.prototype.toLocaleDateString() passing "en-US"
which would look at your code:
dateSelected.toLocaleDateString('en-US')

You could use MomentJS library to keep things simple:
Include the library :
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment.min.js"></script>
document.getElementById("pM1").innerHTML = moment(date1).format('DD/MM/YYYY');
document.getElementById("pM2").innerHTML = moment(date2).format('DD/MM/YYYY');
and in the else:
document.getElementById("pW1").innerHTML = moment(date1).format('DD/MM/YYYY');
document.getElementById("pW2").innerHTML = moment(date2).add(1, 'week').format('DD/MM/YYYY');

Related

Datetime-local set default hours

I'm using the following input :
<input id="creation-from-date" type="datetime-local"/>
I'd like know if there is a way to set default hours like this :
dd/mm/yyyy 00:00
Because the datepicker allows to pick date only, not time so I get an invalid date in JS side because the hours is not set.
I'm using Chrome v73.0.3683.75
Many thanks !
I would use <input type='date' /> and <input type='time' /> instead:
//<![CDATA[
/* external.js */
var doc, bod, I, DateTime; // for use on other loads
addEventListener('load', function(){
doc = document; bod = doc.body;
I = function(id){
return doc.getElementById(id);
}
DateTime = function(dateElement, timeElement, dateInstance){
var t = this;
this.dateElement = dateElement; this.timeElement = timeElement;
this.date = dateInstance instanceof Date ? dateInstance : new Date;
this.dateValue = function(dateInstance){
if(dateInstance instanceof Date)this.date = dateInstance;
var dt = this.date;
return dt.getFullYear()+'-'+(dt.getMonth()+1).toString().replace(/^(\d)$/, '0$1')+'-'+dt.getDate().toString().replace(/^(\d)$/, '0$1');
}
this.showDate = function(dateInstance){
this.dateElement.value = this.dateValue(dateInstance);
return this;
}
this.timeValue = function(dateInstance){
if(dateInstance instanceof Date)this.date = dateInstance;
var dt = this.date;
return dt.getHours().toString().replace(/^(\d)$/, '0$1')+':'+dt.getMinutes().toString().replace(/^(\d)$/, '0$1');
}
this.showTime = function(dateInstance){
this.timeElement.value = this.timeValue(dateInstance);
return this;
}
this.showDate().showTime();
this.dateChange = function(changeFunc, noTimeFunc){
this.dateElement.oninput = function(){
var v = this.value, s = t.timeElement.value;
if(v === '')v = this.value = t.dateValue(noTimeFunc(t));
if(s === '')s = t.timeValue(this.date);
t.date = new Date(v+' '+s); changeFunc(t.date, t);
}
return this;
}
this.timeChange = function(changeFunc, noTimeFunc){
this.timeElement.oninput = function(){
var v = this.value, s = t.dateElement.value;
if(v === '')v = this.value = t.timeValue(noTimeFunc(t));
if(s === '')s = t.dateValue(this.date);
t.date = new Date(s+' '+v); changeFunc(t.date, t);
}
return this;
}
}
var dateElement = I('date'), timeElement = I('time');
function threeHoursLater(){
return new Date(Date.now()+10800000);
}
var dt = new DateTime(dateElement, timeElement, threeHoursLater()); // 3 hours from now - initial date time set
function consoleIt(dateInstance){
console.log('display of dt.date --> '+dateInstance.toString());
console.log('dt.date for server --> '+dateInstance.getTime());
}
consoleIt(dt.date);
dt.dateChange(function(r){
consoleIt(r);
}, threeHoursLater).timeChange(function(a){
consoleIt(a);
}, threeHoursLater);
}); // end load
//]]>
<input id='date' type='date' />
<input id='time' type='time' />
Close those inputs and see what happens! Oh, make sure you validate those dates on your Server. The Client can be altered.
I have update the above code to include a DateTime constructor. The arguments should be clear.
PS
I noticed that there is an issue in Firefox 67.0 (64-bit) with change events, on Elements that do not receive focus first, therefore .onchange was changed to .oninput, which seems to work across the board.
Try to add default date for it
document.getElementById("creation-from-date").value = setDefautValue();
function setDefautValue() {
var date = new Date(); // today
date.setUTCHours(0, 0, 0, 0); //set default time 00:00 AM
const dStr = date.toISOString()
// remove seconds and milliseconds
return dStr.substring(0, dStr.indexOf(':', dStr.indexOf(':')+1))
}
You can try using Javascripts date:
$("creation-from-date").val(new Date().toLocalString());
// toLocalString() will return the local time while toISOString() will return the UTC time.
Here a good jQuery extension that is pretty useful for initializing datetime and datetime-local inputs:
// To initialize, simply call the method:
$('input[type="datetime-local"]').setNow();
Hope this helps.

How to stop incorrect value in datepicker when previous data select in JavaScript?

Here, I got code for disable date in datepicker. when user select previous date then it alert to put a valid future date. It's working.
But It's printing whatever we select previous date. I want to stop print when previous date select. Thanks in advance.
<div class="col-md-8">
<input class="form-control datepicker" id="datepicker" onchange="checkDate()" required type="date" name="smexdate" value="<?=$promotion_details['expiry_date']?>" data-date-format="yyyy-mm-dd">
</div>
and JavaScript below.
function checkDate() {
var selectedText = document.getElementById('datepicker').value;
var selectedDate = new Date(selectedText);
var now = new Date();
if (selectedDate < now)
{
alert("Date must be in the future");
return false;
}
}
How about this?
var lastData;
function checkDate() {
var selectedText = document.getElementById('datepicker').value;
var selectedField = document.getElementById('datepicker');
var selectedDate = new Date(selectedText);
var now = new Date();
if (selectedDate < now)
{
console.log(lastData)
selectedField.value = (lastData) ? lastData : '';
alert("Date must be in the future");
return 0;
}
var theDate = new Date(selectedText);
var month = theDate.getMonth() + 1;
var date = theDate.getDate();
var year = theDate.getFullYear();
lastData = year + "-" + String("0" + month).slice(-2) + "-" + String("0" + date).slice(-2);
}

How I can interpret the correct date in Javascript when the year is of the format yy?

I have defined an input that accepts only dates in HTML.
The user can enter the date manually or by using a Calendar which is defined in javascript.
I am using Javascript and Jquery to convert the input to a date:
var lStartDateText = $j("#DateStarte").val();
var lEndDateText = $j("#DateEnd").val();
var lEffStartDate = new Date(lStartDateText);
var lEffEndDate = new Date(lEndDateText);
My problem is that when the user enters the following date manually 1/1/50 is interpreted as 1/1/1950 but 1/1/49 is interpreted as 1/1/2049. I want it always to be interpreted as 20xx.
On the other hand the Calendar allows the user to choose a year from 2006 to 2021 in case the user wants to choose a date from it and not enter it manually.
Hope I can get some help here ??
Try this
var lStartDateText = $j("#DateStarte").val();
var lEndDateText = $j("#DateEnd").val();
var lEffStartDate = ReFormatDate(lStartDateText);
var lEffEndDate = ReFormatDate(lEndDateText);
function ReFormatDate(dateString) {
var dateParts = dateString.split("/");
if (dateParts[2].length === 2) {
dateParts[2] = "20" + dateParts[2];
}
return new Date(dateParts.join("/"));
}
use this
var lStartDateText = "1/1/50" ;
var lEndDateText = "1/1/49" ;
var res = lStartDateText.slice(4);
var starttext = lStartDateText.replace(res,"20"+res);
var res1 = lEndDateText.slice(4);
var endtext = lEndDateText.replace(res1,"20"+res1);
alert(starttext);
alert(endtext);
var lEffStartDate = new Date(starttext);
alert("start date"+lEffStartDate);
var lEffEndDate = new Date(endtext);
alert("End Date"+lEffEndDate);
If you know your getting the last 2 digits of the year (50), and you know you always want to add the first 2 digits, which are constant (20), that's a slight modification to your code:
var lStartDateText = '20' + $j("#DateStarte").val();
var lEndDateText = '20' + $j("#DateEnd").val();
Note that this is not particularly robust, e.g. if the user enters text which is not a date you might end up with a string like '20hi', but that may be outside the scope of your question and it will be parsed as an invalid date.
$('#year').on('change keyup', function() {
var y = $('#year').val();
if (y.length === 2) {
y = '20' + y
}
if (y.length === 4) {
var dateY = new Date();
dateY.setFullYear(y);
$('#result').html(dateY);
} else {
$('#result').html('No YY or YYYY date found');
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<label for="year">Enter year (YY or YYYY)</label>
<input id="year" type="text">
<div id="result"></div>
i hope it's will be help you.
$('#year').on('change keyup', function() {
var right_date = $('#year').val();
var data = $('#year').val().split('/');
if (data[2].length == 2){
var twoDigitsCurrentYear = parseInt(new Date().getFullYear().toString().substr(0,2));
$('#result').html(data[0]+'/'+data[1]+'/'+twoDigitsCurrentYear + data[2]);
}
else {
$('#result').html(right_date);
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<label for="year">Enter year (YY or YYYY)</label>
<input id="year" type="text" placeholder="dd/mm/yy">
<div id="result"></div>

How to compare date with current date for applying logic

<script>
$(document).ready(function(){
if(date.now()>($("[id$=clear2]").val)+2){
$("[id$=clear]").val("");
$("[id$=clear2]").val("");// date value
$("[id$=clear3]").val("");
}
});
</script>
I want to check that current date(dd/mm/yyyy) is greater than date(dd/mm/yyyy) value + 2 days .I was working several scenarios .that by removing if condition it is working fine .By using this it is not working well .Can you show some solution so that i can move forward
Try this:
var d1 = '31/11/2015'.split('/');
var d2 = '27/12/2015'.split('/');
var date1 = new Date(d1[2],d1[1],d1[0]); // YYYY,MM,DD
var date2 = new Date(d2[2],d2[1],d2[0]);
var numOfDaysToAdd = 2;
date2.setDate(date2.getDate() + numOfDaysToAdd);
if (date1.getTime() < date2.getTime()) {
alert('date1 is before date2');
}
Working with dates in javascrip:
javascript
$(document).ready(function () {
var today = new Date();
var tomorrow = new Date(today);
tomorrow.setDate(today.getDate() + 1);
$("#today").val(today.toUTCString());
$("#tomorrow").val(tomorrow.toUTCString());
$("#checkDate").click(function () {
var newDate = new Date($("#today").val());
newDate.setDate(newDate.getDate() + 2);
var parsedTomorrow = new Date($("#tomorrow").val());
var comRes = newDate > parsedTomorrow;
alert(comRes);
});
});
HTML
<input type="text" id="today" />
<input type="text" id="tomorrow" />
<input type="button" id="checkDate" />
DEMO
Use JavaScript Date Object to compare dates in javascript.

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