PDA

View Full Version : Date format in Javascript


jamesthecat
04-16-2003, 02:52 PM
Hi,
I'm trying to display the current date in an asp.net text box using Javascript.
I'm using the following script which works but doesn't display the date in the format I need. ie dd/mm/yyyy

<script language="JavaScript">
document.insert.item_date.value = new Date();
</script>

Many thanks.

HairyTeeth
04-16-2003, 03:18 PM
Try this:

<html>
<head>
<title>Date Demo</title>
<script type="text/javascript" language="javascript">
<!--;

function doDate(){
var box = document.insert.item_date
var now = new Date();
var theDay = now.getDate();
var theMonth = now.getMonth() + 1;
var theYear = now.getFullYear();
if(theDay < 10) theDay = "0"+theDay;
if(theMonth < 10) theMonth = "0"+theMonth
var theDate = theDay + "/" + theMonth +"/"+theYear;
box.value = theDate;
}
//-->
</script>
</head>
<body onload="doDate()">
<form name="insert">
<input type="text" name="item_date" value="" />
</form>
</body>
</html>

beetle
04-16-2003, 03:31 PM
Or, if you'd like, you can use my Date class (http://www.peterbailey.net/dev/jsclasses/) :D

<script type="text/javascript" src="path/to/file/date.class.js"></script>
<script type="text/javascript">
document.insert.item_date.value = new MyDate().getDate( "m/d/Y" );
</script>

jamesthecat
04-16-2003, 03:57 PM
Thanks guys!
Sorry Hairyteeth but I couldn't get yours to work but I'm sure thats because I was doing something stupid. :(

Beetle, thank you - that works but how do I make it display dd/mm/yyyy as opposed to mm/dd/yyyy?

A million thanks to you both.

JTC
:)

jamesthecat
04-16-2003, 04:00 PM
duhhhhhh!
Please ignore my last post about the dd/mm thing.
I just realised what to do.
I'm a right thicko today.

Many thanks Beetle.

JTC

beetle
04-16-2003, 04:05 PM
No problem. If you ever need to change it, it uses the PHP date() function codes for output, which you can reference here (http://www.php.net/manual/en/function.date.php)

For exmaple: changing to a 2-digit year just requires a lower-case 'y'

d.getDate( "d/m/y" );

:thumbsup: