Learn how to showcase the current date by utilizing JavaScript arrays and the getDate method!

I have been struggling to format the date as follows:

"Today is Sunday, the 31st day of March in the year 2019."

I am working with JavaScript in an HTML5 document. Below is the code I have so far, and I would appreciate any help. I prefer not to rely on any third-party libraries, only using basic JavaScript.

<script type="text/javascript>
  var monthName = new Array();
  monthName[0] = "January";
  monthName[1] = "February";
  monthName[2] = "March";
  monthName[3] = "April";
  monthName[4] = "May";
  monthName[5] = "June";
  monthName[6] = "July";
  monthName[7] = "August";
  monthName[8] = "September";
  monthName[9] = "October";
  monthName[10] = "November";
  monthName[11] = "December";

  var myYear = today.getFullYear();
  var myDate = today.getDate();

  var dayExt = "th";

  if ((myDate == 1) || (myDate == 21) || (myDate == 31)) dayExt = "st";
  if ((myDate == 2) || (myDate == 22)) dayExt = "nd";
  if ((myDate == 3) || (myDate == 23)) dayExt = "rd";

  var extDate = myDate + dayExt;

  document.write(extDate + "Today is the day of ");
  document.write(monthName[today.getMonth()] + " in the year ");
  document.write(myYear + ".");
</script>

Current output: No result

Expected output: Today is Sunday, the 31st day of March in the year 2019.

Answer №1

Here's a simple approach to tackle this task. It involves:

  1. Understanding array creation and initialization
  2. Checking multiple conditions efficiently
  3. Utilizing template notation for string creation - ${expression_goes_here}
  4. Inserting content on the page without disrupting existing elements, avoiding dreaded document.write()
  5. Ensuring code runs after the whole page is loaded before interacting with expected content

"use strict";
window.addEventListener('load', function()
{
var monthNames = ['January','Febuary','March','April','May','June','July','August','September','October','November','December'];
var dayNames = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
var today = new Date();

var dayName = dayNames[today.getDay()];
var monthName = monthNames[today.getMonth()];
var dayOfMonth = today.getDate();

var ext = dayOfMonth % 10;
switch (ext)
{
case 1: ext = "st"; break;
case 2: ext = "nd"; break;
case 3: ext = "rd"; break;
default:ext = "th"; break;
}

var text = `Today is ${dayName}, the ${today.getDate()}${ext} day of ${monthName} in the year ${today.getFullYear()}`;
var textElem = document.createTextNode(text);
document.body.appendChild(textElem);
}, false );

  1. Create arrays with all data directly instead of inserting elements one by one.
  2. Explore using the switch statement for efficient code branching.
  3. Embrace template literals for cleaner string concatenation.
  4. Avoid using document.write() to prevent erasing existing content on the page.
  5. Wrap code inside an event listener to ensure it only executes after full page load.

Below is the form to handle the load event:

window.addEventListener('load', callThisFuncWhenLoadEventReceived, false);

You can either specify a named function or use an anonymous function like demonstrated here.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can diverse array elements be divided into separate arrays based on their object type in JavaScript?

Looking to create new arrays based on objects with similar attributes from an existing array? Here's how: Starting with this [ {name: "test", place: "country"}, {name: "walkAndEat", Long: 100, Lat: 15, Location: "place name"}, {name: "te ...

Can select2 and a jQuery Virtual Keyboard work together seamlessly?

Is there a method to implement a jQuery virtual keyboard for inputting into a Select2 select box? The issue is that the dropdown in the Select2 component closes automatically when clicked away from, preventing the use of a web-based virtual keyboard. If ...

When a custom header is added, cookies are not included in cross-origin jQuery AJAX requests

An issue arises when sending an ajax request from our main domain to a subdomain (cross-origin) through jQuery. Despite having CORS implemented and functional, we encounter a problem when attempting to include a custom header in the request. The presence o ...

Implement a Codeigniter model that utilizes JavaScript to insert an ID

Is there a way to retrieve the productid value in PHP code? function getunitstock(){ var productid = document.getElementById('product').value <?php $prodbyid = $this->pos_model->get_productbyid(+productid+)?> document. ...

Tips for eliminating fade effect during hover in networkD3 chart in R

Currently, I have been exploring the usage examples of networkd3 in r I am curious if there is a way to eliminate the hover effect where everything else fades when hovering over a specific node in the graph. For reference, check out "Interacting with igra ...

What is the best method for storing a model in a database?

Hello, I am currently attempting to save a model to the database. I am simply inputting the value of a title in order to save it, as my id is set to auto increment. However, I have encountered an issue where my attempts have been unsuccessful. Can someone ...

rearranging the sequence of buttons using JavaScript

I am faced with the challenge of making a series of buttons draggable and droppable within a parent div without using any external libraries at the request of the client. Although I could have easily accomplished this task with jQuery, it's an opportu ...

What is the method to close the picker when using type="datetime-local"?

Currently, I am utilizing Vue with the "datetime-local" type for input. While I can successfully select the date and time, my goal is to have the picker close automatically after a selection has been made. I've experimented with adding an onchange ev ...

Use Javascript to display specific div elements by clicking a button

I could really use some assistance, When I attempt to display the select div by clicking the button, the "id" that PHP generates returns a null response in the console. The requirement is to only show the div when clicking on the "Quick Quote" button. Pro ...

What makes this CSS causing render blocking?

I've been meticulously following the Google PageSpeed guidelines in order to optimize the performance of my website. Upon running an analysis, Google provides me with a score based on their set guidelines. There's one particular guideline that ...

What is the best method for applying classes to a collection of DOM elements with jQuery?

I attempted two different methods of iterating through the arrays, but encountered the same error: addClass is not function First attempt using a for loop: function game(){ var cards = $('.card'); function initialize(){ for ...

Troubleshooting issues with rowspan in a Datatable

I am currently utilizing jQuery DataTables to display my grid data and implementing the rowspan concept with the rowsGroup option. Initially, it works well by spanning some rows and looking visually pleasing, but eventually, it starts failing. Here are so ...

Setting up PostgreSQL database integration with Node.js

I want to remove certain entries from a PostgreSQL database based on creation/expiry dates, but I only want this to happen when the Node server first starts. Currently, I have added the line DELETE FROM ....db WHERE date <= CURRENT_DATE to the main r ...

Verify whether the current directory includes a package.json file with a matching name value

When I run a custom command in the terminal, I am attempting to achieve two objectives: Verify if there is a package.json file in the current directory (similar to checking for the existence of process.cwd() + '/package.json'). Determine if the ...

Is it possible to have a hidden div box within a WordPress post that is only visible to the author of the

How can I create a div box with "id=secret" inside a post that is only visible to the author of the post? I initially made it for the admin, but now I want the id to be visible exclusively to the post's author. For instance: If the author is curren ...

The Angular service encounters issues when interacting with REST API

Within my application, a template is utilized: <div class="skills-filter-input" ng-class="{'hidden-xs': skillsFilterHidden}"> <input type="text" ng-model="skillQuery" ng-change="filterSkills()" placeholder="Filter skills" class="filter- ...

What steps should I take to adjust the price when multiple items are chosen?

I am working on a school project that requires JavaScript programming assistance. You can view the code here: https://jsfiddle.net/zvov1jpr/3/ HTML: <script src="java.js"></script> <div id="formular"> <div id=&qu ...

Python ValueError occurs when attempting to insert one array into another

I'm facing an issue trying to merge two arrays, suspecting a problem with the array dimensions as it triggers a ValueError. The exponential data I'm attempting to combine resides in EXP and displays correctly when printed out, but has a length of ...

Dynamically getting HTML and appending it to the body in AngularJS with MVC, allows for seamless binding to a

As someone transitioning from a jQuery background to learning AngularJS, I am facing challenges with what should be simple tasks. The particular issue I am struggling with involves dynamically adding HTML and binding it to a controller in a way that suits ...

The selection elements fail to reset correctly

I'm currently working on an Angular 4 application where I have a form that includes a select element inside a box. <div class="form-group"> <label for="designation">Designation</label> <select [class.red-borde ...