We always use the Javascript Datetime Format in our frontend application. For that, we will show you a simple tutorial about how to use Javascript Datetime Format effectively in your Frontend web application.
Default Javascript Format DateTime
Default Javascript Format DateTime is a long date with time. Here's an example of javascript default DateTime.
<html>
<head>
<title>Javascript Datetime</title>
</head>
<body>
<h1 id="datetime"></h1>
<script type="text/javascript">
var datetime = document.getElementById('datetime');
var defaultdatetime = new Date();
datetime.innerHTML = defaultdatetime;
</script>
</body>
</html>
That example will display full javascript datetime on the screen.
Human Readable DateTime
We can display a DateTime in more human readable using this method.
<script type="text/javascript">
var datetime = document.getElementById('datetime');
var d = new Date();
var formatted = d.getDate()+"-"+(d.getMonth()+1)+"-"+d.getFullYear()+" "+d.getHours()+":"+d.getMinutes();
datetime.innerHTML = formatted;
</script>
Here's a result.
24-12-2016 6:11
This is not really pretty code, but easier to implement and compatible with all browser without adding another javascript libraries.
We have to remember that getMonth() method returns month between 0 to 11, so we have to add 1 to match the current month.
Example to show full date with day name.
<script type="text/javascript">
var datetime = document.getElementById('datetime');
var dayname = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var d = new Date();
var formatted = dayname[d.getDay()]+", "+d.getDate()+"-"+(d.getMonth()+1)+"-"+d.getFullYear()+" "+d.getHours()+":"+d.getMinutes();
datetime.innerHTML = formatted;
</script>
Result.
Saturday, 24-12-2016 6:11
Example to show date with the month name.
<script type="text/javascript">
var datetime = document.getElementById('datetime');
var monthname = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
var d = new Date();
var formatted = monthname[d.getMonth()]+" "+d.getDate()+", "+d.getFullYear();
datetime.innerHTML = formatted;
</script>
Result
December 24, 2016
That's was very easy using pure javascript for format DateTime.
That just the basic. If you need more deep learning about HTML, CSS, Javascript or related you can take the following cheap course:
- HTML & HTML5 For Beginners (A Practical Guide)
- Web - HTML
- Learn HTML, CSS, JAVASCRIPT
- JavaScript:
- Learn JavaScript Fundamentals
- Learning JavaScript Shell Scripting
Thanks.