I have a url that change every day based on today's date, for example:
http://www.newspaper.com/edition/20141227.html
where 20141227 is in the format YYYYMMDD.
Can I include the date using JavaScript? If possible, how would I do that?
I think following steps will help you to achieve the functionality your are looking for
1.Convert the today's date or any date to intended format that is "YYYYMMDD" in your case.
2.Then append it to your URL.
Please look into code snippet for details. Note you just need to hover over URL to know what it is pointing to.
Date.prototype.toMyString = function () {
//If month/day is single digit value add perfix as 0
function AddZero(obj) {
obj = obj + '';
if (obj.length == 1)
obj = "0" + obj
return obj;
}
var output = "";
output += this.getFullYear();
output += AddZero(this.getMonth()+1);
output += AddZero(this.getDate());
return output;
}
var d = new Date();
var link = document.getElementById("link");
link.setAttribute("href","/yourchoiceofURL?t="+d.toMyString());
<ul>
<li><a id="link" href="#">Any URL</a></li>
</ul>
var date = new Date().toDateString("yyyyMMdd");
then paste the date in building the URL
url = "http://blahblahblaj.com/"+date
You can try the below code. Hope this helps.
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10){dd='0'+dd};
if(mm<10){mm='0'+mm};
today = yyyy+mm+dd;
var new_url=document.URL+"/"+today+".html";
console.log(new_url);
Here's a simpler method that works
<script>
var link = document.getElementById('link'); // ref. to your anchor tag
var d = new Date,
date = d.getDate(),
month = d.getMonth()+1, // Months in JavaScript are 0 indexed
year = d.getFullYear();
if(date < 10) date = ("0" + date);
if(month < 10) month = ("0" + month);
link.href = ("STATIC_URL/" + year + month + date);//Concatenating three numbers, kind of a hack
</script>
This is as simple as it gets.
Thanks for all the answers colleagues. For Dnyanesh, I tried the code in http://jsfiddle.net/ can work well. I try to enter into an html page like this, why can not run perfectly. Where is the mistake?
<html>
<head>
<script type='text/javascript'>
Date.prototype.toMyString = function () {
//If month/day is single digit value add perfix as 0
function AddZero(obj) {
obj = obj + '';
if (obj.length == 1)
obj = "0" + obj
return obj;
}
var output = "";
output += this.getFullYear();
output += AddZero(this.getMonth()+1);
output += AddZero(this.getDate());
return output;
}
var d = new Date();
var link = document.getElementById("link");
link.setAttribute("href","http://www.pressdisplay.com/pressdisplay/pageview.aspx?issue=1245"+d.toMyString()+"00000000001001");
</script>
</head>
<body>
<a id="link" href="#">Any URL</a>
</body>
</html>
Thank you for all, all of the recommended code runs fine. If you want to put into the HTML code , add the following code to be loaded in the browser :
//<![CDATA[
window.onload=function(){
....javascript code here....
}//]]>
Related
I'm trying to convert a MM/DD/YYYY date to a long date. So for example, 02/16/2020 would convert to something like 16/02/2020.
Is there a way to make this date conversion accurately?
You need to specify the original format of the time, and then convert it to a new format.
const date = "02/16/2020";
alert(moment(date, "MM/DD/YYYY").format('DD/MM/YYYY'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
Use moment for date formatting:
Sample Code:
moment('02/16/2020').format('16/02/2020');
You can play with date by moment.js. It is very useful tool for javascript developer.
Momemet Js Document
For dynamic value:
moment(yourDate, 'MM/DD/YYYY').format('DD/MM/YYYY');
Here, yourDate is your dynamic value date.
check this. its work.
function formatDate(date) {
var d = new Date(date),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;
return [day,month,year].join('/');
}
document.getElementById('res').innerHTML = formatDate('02/16/2020') ;
<div id="res">res</div>
2 || 1 liners ?
var src = '02/16/2020'
var a = src.split('/');
console.log(a.concat(a.splice(0, 2)).join('/'));
console.log(src.replace(/(\d+)\/(\d+)\/(\d+)/, '$3/$1/$2'));
If you want a conversion just between the exact formats you have mentioned:
function dfConvert(f) {
var farr = f.split("/");
return `${farr[1]}/${farr[0]}/${farr[2]}`;
}
var input = "02/16/2020";
console.log(`input: ${input}`)
console.log(`output: ${dfConvert(input)}`);
If you want the actual date object and from that you want your mentioned format for some reason:
function toDate(f) {
var farr = f.split("/");
return new Date(parseInt(farr[2]), parseInt(farr[0])-1, parseInt(farr[1]))
}
function dfConvert(f) {
var d = toDate(f)
var day = d.getDate()
var month = (d.getMonth() + 1)
var year = d.getFullYear()
return `${((day.toString().length <= 1) ? "0": "")}${day}/${((month.toString().length <= 1) ? "0": "")}${month}/${year}`
}
var input = "02/16/2020"
console.log(`input: ${input}`)
console.log(`output: ${dfConvert(input)}`)
Hope it helps
How to get the date trimmed of exactly in the format of (dd/mm/yyyy) in the following implementation of my code using JavaScript
<script type="text/javascript" language="javascript">
function disptextbox() {
var d = new Date();
var x = document.getElementById("ddlweeklist").value;
switch (x)
{
case "1":
document.getElementById("txtstart").value = d.toDateString();
document.getElementById("Txtend").value = d.toDateString();
break;
case "2":
var firstday = new Date(d.setDate(d.getDate() - d.getDay()));
var lastday = new Date(d.setDate(d.getDate() - d.getDay() + 6));
document.getElementById("txtstart").value= firstday.toDateString();
document.getElementById("Txtend").value = lastday.toDateString();
break;
case "3":
var date = new Date();
var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
var lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);
document.getElementById("txtstart").value = firstDay.toDateString();
document.getElementById("Txtend").value = lastDay.toDateString();
break;
case "4":
var firstd = new Date(d.getFullYear(), 0, 1);
var lastd = new Date(d.getFullYear(), 11, 31);
document.getElementById("txtstart").value = firstd.toDateString();
document.getElementById("Txtend").value = lastd.toDateString();
break;
}
}
</script>
in this code of implementation I want the date format to be in dd/mm/yyyy format ...I will be glad if any one help me over this this function call occurs on the drop down change especially...I am ok with functionality of the code but not comfortable in handling with DATE FUNCTIONS...
so please suggest me where I can get good examples for implementing date functions...in javascript
You can do this if you want dd/mm/yyyy format date:
new Date().toISOString().substr(0,10).replace(/(\d{4})-(\d{2})-(\d{2})/g,"$3/$2/$1");
I've written a couple of prototypes for dates than you may find useful:
Date.prototype.dateStr=function(split){
split=split===undefined?"-":split;
var output=parseInt(parseInt(this.getMonth())+1).toString().toLength(2);
output+=split;
output+=this.getDate().toString().toLength(2);
output+=split;
output+=this.getFullYear().toString().toLength(4);
return output;
}
Date.prototype.FOM=function(){
return new Date(this.getFullYear(),this.getMonth(),1);
}
String.prototype.toLength=function(len,fill){
fill=fill===undefined?"0":fill;
var outStr=this.toString();
while (outStr.length<parseInt(len)){
outStr=fill+outStr;
}
return outStr;
}
Technically, the 3rd one is a string prototype, but whatever. new Date().FOM() will give you a javascript date object for the first day of whatever month you pass it. new Date().dateStr("/") will give you a string - mm/dd/yyyy format - with separators as whatever you pass it, default "-".
That last one will take a string and make it a certain length by prepending the 'fill' - default '0'.
You could try with this function:
function toDateString(mydate) {
var day = mydate.getDate();
var month = mydate.getMonth();
day = day < 10 ? '0'+day : day;
month = month < 10 ? '0'+month : month;
return day + '/' + month + '/' + mydate.getYear();
}
You could then use it this way:
alert(toDateString(firstday)); // I'm using alert just for demonstration purposes
Here is a DEMO you could fiddle with.
EDITED: Learning from #Helpful's answer below, my above function could be used as a prototype to better fit the way you wrote up your code like this:
Date.prototype.toDateString=function() {
var day = this.getDate();
var month = this.getMonth();
day = day < 10 ? '0'+day : day;
month = month < 10 ? '0'+month : month;
return day + '/' + month + '/' + this.getYear();
}
so you could call it this way:
alert(thedate.toDateString()); // This is how you used it, if I understood it well.
Here is a DEMO of that.
Pass any data format
function convertDate(inputFormat) {
function pad(s) { return (s < 10) ? '0' + s : s; }
var d = new Date(inputFormat);
return [pad(d.getDate()), pad(d.getMonth()+1), d.getFullYear()].join('/');
}
hope this will help you sure.....
Is there any way to set the format of <input type="date" /> ? if no then how can i set date in this field using JavaScript in the default format of type="date". how can i get what will be the format of this field?
EDIT :
Actually i want to show native date-picker of mobile device that's why i picked this type of input. if is there any alternate for that field that also will b good to have.
Sorry if i said anything stupid. Please guide me
The format is YYYY-MM-DD. You cannot change it.
$('#myinput').val('2013-12-31'); sets value
new Date().toISOString().split('T')[0];
try this :)
function getDefaultDate(){
var now = new Date();
var day = ("0" + now.getDate()).slice(-2);
var month = ("0" + (now.getMonth() + 1)).slice(-2);
var today = now.getFullYear()+"-"+(month)+"-"+(day) ;
return today;
}
$(document).ready(function(){
$("#dateid").val( getDefaultDate());
});
Canadian locale happens to follow the same format, too:
new Date().toLocaleDateString('en-CA')
Easier than the above is
var today = new Date().toISOString().substring(0,10); # "2013-12-31"
It's ugly, but it works. :/
var today = new Date().toLocaleString('en-GB').split(' ')[0].split('/').reverse().join('-');
Please check this https://stackoverflow.com/a/9519493/1074944 and try this way also $('input[type="date"]').datepicker().prop('type','text'); check the demo
I think this can help
function myFormatDateFunction(date, format) {
...
}
jQuery('input[type="date"]')
.each(function(){
Object.defineProperty(this,'value',{
get: function() {
return myFormatDateFunction(this.valueAsDate, 'dd.mm.yyyy');
},
configurable: true,
enumerable : true
});
});
function getDefaultDate(curDate){
var dt = new Date(curDate);`enter code here`
var date = dt.getDate();
var month = dt.getMonth();
var year = dt.getFullYear();
if (month.toString().length == 1) {
month = "0" + month
}
if (date.toString().length == 1) {
date = "0" + date
}
return year.toString() + "-" + month.toString() + "-" + date.toString();
}
In function pass your date string.
#cOnstructOr provided a great idea, but it left a comma in place
var today = new Date().toLocaleString('en-GB').split(' ')[0].slice(0,-1).split('/').reverse().join('-');
fixes that
What you want to do is fetch the value from the input and assign it to a new Date instance.
let date = document.getElementById('dateInput');
let formattedDate = new Date(date.value);
console.log(formattedDate);
Here is a simple answer,
Since this is a string, we can use Javascript String slice method to rearrange the characters
<input type="date" id="idate" name="tno"><br>
<button onclick="run()">Run</button>
<p id="demo"></p>
<script>
function run() {
var d = document.getElementById("idate").value;
document.getElementById("demo").innerHTML = d.slice(8, 10) + "/" + d.slice(5, 7) + "/" + d.slice(0, 4);
}
</script>
Source
https://www.w3schools.com/jsref/jsref_slice_string.asp
i have problem with date validation in javascript
the problem is i have popup calendar the return a date value
i want to check the date in javascript before send it to parent page
in popup calendar.aspx
function passDateValue(DateValue)
{
window.returnValue=DateValue;
window.close();
return false;
}
in popup calendar codebehind
ClientScript.RegisterStartupScript(GetType(), "SelectDate", "passDateValue('" + clrPopUp.SelectedDate.ToShortDateString() + "')", true);
the function that call the popup calendar and check the returned value
function Calendar_popup(tbClientID)
{
var today = new Date();
var Day = today.getDate();
var Month = today.getMonth()+1;
var Year = today.getFullYear();
if(Month<10){Month = '0'+Month;}
if(Day<10){Day = '0'+Day;}
var todayFormat = Day + "/" + Month + "/" + Year;
datevalue = window.showModalDialog("Calendar_Dialog.aspx?ctlid=" + tbClientID, '',"dialogHeight:250px;dialogWidth:300px;");
var startdate = Date.parse(datevalue);
var enddate = Date.parse(todayFormat);
if (startdate>enddate)
{alert('BirthDate Must be less than today');
return;
}
}
is there anyway to check date ?
thanks!
Check out date.js, specifically...
http://code.google.com/p/datejs/wiki/APIDocumentation#compare
Compares the first date to the second date and returns an number
indication of their relative values. -1 = this is < date. 0 =
values are equal. 1 = this is > date.
The isAfter() and the isBefore() methods might be useful for your problem :)
Download the library here:
http://code.google.com/p/datejs/downloads/detail?name=date.js&can=2&q=
I am looking for a time output using jQuery, for example, would be great to know what time it is on the visitor's browser and the current day (friday,saturday,monday, etc...).
Is there any way to do it only with jQuery? I don't really like the way javascript handles time issues.
If you recommend any plugin, please tell me wich.
Thanks so much!
Souza.
EDIT:
I'm looking to avoid substring javascript outputs, or convert the results.
Wouldn't be great to use
$("#setime").yourtime("day");
and give me the day?
or
$("#setime").yourtime("hour", 24format);
and give you the hour in any format you need?
?
Try:
var currentTime = new Date();
It's not jQuery but it will do what you want.
You also have:
var month = currentTime.getMonth()
var day = currentTime.getDate()
var year = currentTime.getFullYear()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
To play with.
Perhaps this is what you were looking for?
http://crossbreeze.github.com/jquery-sensible-datetime/
Download here: https://github.com/crossbreeze/jquery-sensible-datetime
If not, here is plain JS for you to reuse
<script type="text/javascript">
var weekday=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday"," Saturday"];
var monthname=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
function formatDate(d) {
var text = "";
text += weekday[d.getDay()] + " ";
text += d.getDate() + " ";
text += monthname[d.getMonth()] + " ";
text += d.getFullYear();
var hh = d.getHours();
var mm = d.getMinutes();
if (hh<10) hh = "0"+hh;
if (mm<10) mm = "0"+mm;
return text +" "+hh+":"+mm;
}
$(document).ready(function () {
var d = new Date();
$("#dateDiv").text(formatDate(d));
});
</script>