w3resource

CoffeeScript: Display the current day and time in the specific format

Coffee Script Basic: Exercise-1 with Solution

Write a CoffeeScript program to display the current day and time in the following format.

Sample Output : Today is : Friday.
Current time is : 4 PM : 50 : 22

HTML Code :

<!DOCTYPE html>
<html>
<head>
<script src="//jashkenas.github.io/coffee-script/extras/coffee-script.js"></script>
  <meta charset="utf-8">
  <title>Display the current day and time in the specific format</title>
</head>
<body>

</body>
</html>

CoffeeScript Code :

today = new Date
day = today.getDay()
daylist = [
  'Sunday'
  'Monday'
  'Tuesday'
  'Wednesday '
  'Thursday'
  'Friday'
  'Saturday'
]
console.log 'Today is : ' + daylist[day] + '.'
hour = today.getHours()
minute = today.getMinutes()
second = today.getSeconds()
prepand = if hour >= 12 then ' PM ' else ' AM '
hour = if hour >= 12 then hour - 12 else hour
if hour == 0 and prepand == ' PM '
  if minute == 0 and second == 0
    hour = 12
    prepand = ' Noon'
  else
    hour = 12
    prepand = ' PM'
if hour == 0 and prepand == ' AM '
  if minute == 0 and second == 0
    hour = 12
    prepand = ' Midnight'
  else
    hour = 12
    prepand = ' AM'
console.log 'Current Time : ' + hour + prepand + ' : ' + minute + ' : ' + second

Sample Output:

"Today is : Tuesday."
"Current Time : 1 PM  : 52 : 30"

Live Demo:

See the Pen coffeescript-exercise-1 by w3resource (@w3resource) on CodePen.



Improve this sample solution and post your code through Disqus.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/coffeescript-exercises/coffeescript-exercise-1.php