Displaying Current Date and Time

To display the current date and time into a HTML page via Javascript, add the following into the <HEAD>...</HEAD> tags

<head>
<script language="Javascript">
<!-- Begin
// written by Shahmat Dahlan: shahmatd@sains.com.my
function LastModified(select) {
  var months=new Array(13);
  months[1]="January";
  months[2]="February";
  months[3]="March";
  months[4]="April";
  months[5]="May";
  months[6]="June";
  months[7]="July";
  months[8]="August";
  months[9]="September";
  months[10]="October";
  months[11]="November";
  months[12]="December";
  var today=new Date();
  var lmonth=months[today.getMonth() + 1];
  var date=today.getDate();
  var year=today.getYear();
  var hours=today.getHours();
  var minutes=today.getMinutes();
  var seconds=today.getSeconds();

  if (hours < 12) {
    suffix="AM";
  } else {
    suffix="PM";
  }
  
  if (seconds < 10) {
    seconds="0" + seconds;
  }
 
  if (year < 2000) {
    year = year + 1900;
  }
  
  if (select == "dateOnly") {
    myvar = lmonth + " " + date + ", " + year;
  } else {
    if (select == "timeOnly") {
      myvar = hours + ":" + minutes + ":" + seconds + suffix;
    } else if (select == "full") {
      myvar = hours + ":" + minutes + ":" + seconds + suffix + " " + lmonth + " " + date + ", " + year;
    }
  }
  
  document.write(myvar);
  return;
}
// End -->
</script>
</head>

To call the LastModified function, simply do the following, and to display either dateOnly, timeOnly or full, simply include these three keywords as shown below:

<script language="Javascript">
<!--
  LastModified("dateOnly"); // change to timeOnly to display the current time only or full to display the full
                            // date and time
// -->
</script>

Back to top

 

Back to SarawakNet.com