How to style date strings in JavaScript, jQuery, or CSS

Below are dates that need formatting:

7-sep, 14-sep, 21-sep, 28-sep,
5-oct,12-oct, 19-oct,26-oct,
2-nov, 9-nov, 16-nov, 23-nov,30-nov,
7-dec,14-dec, 21-dec,28-dec-2013.

Is there a way to tidy them up using JavaScript, jQuery, or CSS? Ideally, I would like to present them in a table format similar to this:

DATES | PRICE | NOTES

Answer №1

VIEW DEMO

let currentDate = new Date();
let datesArray = [];
let shortMonths = new Array('jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec');
let fullMonths = new Array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');
let inputDates = "7-sep, 14-sep, 21-sep, 28-sep, 5-oct,12-oct, 19-oct,26-oct,...
var xDate = inputDates.split(',');
$.each(xDate, function (i, val) {
    let dateParts = ($.trim(val)).split('-');
    let newDate = new Date(shortMonths.indexOf(dateParts[1]) + 1 + ',' + dateParts[0] + ',' + currentDate.getFullYear());
    let dayOfMonth = newDate.getDate();
    let formattedDate = dayOfMonth + ([, 'st', 'nd', 'rd'][/1?.$/.exec(dayOfMonth)] || 'th') + ' ' + fullMonths[newDate.getMonth()] + ' ' + newDate.getFullYear();
    datesArray.push(formattedDate);
});
console.log(datesArray);

Updated VIEW DEMO

$.each(datesArray, function (i, val) {
    $('tbody').append('<tr><td>' + val +
        '</td><td>Price Here</td><td>Note Here</td></tr>');
});

This code snippet has been enhanced with a table element to display the processed dates.

Answer №2

To efficiently handle the dates, you will need to process them based on their existing format. If the dates are in string form, one approach could be to tokenize them into an array and extract each date individually. Subsequently, a basic loop can be utilized to generate table rows.

var dates = "7-sep, 14-sep, 21-sep, 28-sep, 5-oct,12-oct, 19-oct,26-oct, 2-nov, 9-nov, 16-nov, 23-nov,30-nov, 7-dec,14-dec, 21-dec,28-dec-2013.";    
dates = dates.substring(0, dates.length - 1).replace(' ', '');
var datesArray = dates.split(',');
for (var i = 0; i < datesArray.length; i++) {
    $('tbody').append('<tr><td>' + datesArray[i] +
        '</td><td>Price Here</td><td>Note Here</td></tr>');
}

For example usage, refer to: http://jsfiddle.net/FuY38/

Answer №3

Explore the capabilities of moment.js by visiting http://momentjs.com/

This library is extremely efficient and provides much more versatility compared to traditional Date object methods.

Utilizing moment.js enables you to achieve tasks like:

var current_year = new Date().getFullYear();
var d = moment('7-sep' + ' ' + current_year);
d.format("Do MMMM YYYY");

Resulting in the output "7th September 2013"

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

Display debugging information in the console using bunyan

child.log.info('info'); child.log.debug('debug'); When running the command: node app.js | bunyan -o short -l debug I am encountering an issue where only INFO messages are displayed and DEBUG messages are not showing up. I want to be ...

Ways to showcase HTML table in a four-column layout/grid

Delving into Dynamic HTML table creation, I'm currently using jquery for rendering purposes. At the moment, I am only displaying the table. The Goal I aim to segment my table into four columns or a grid structure Something akin to this: https://i. ...

Error: The function setEmail is not defined. (In 'setEmail(input)', 'setEmail' is not recognized) (Cannot utilize hooks with context API)

App.js const[getScreen, showScreen] = useState(false); const[getEmail, setEmail] = useState(""); <LoginScreen/> <LoginContexts.Provider value={{getEmail,setEmail,getScreen,showScreen}}> {showScreen?<Screen2/>:<LoginScre ...

The React Native Expo is throwing an error stating that it is unable to locate the module 'minizlib'

At the instructions available in the read.me of https://github.com/react-community/create-react-native-app Upon selecting my template using the expo init command, I encountered the following error: Cannot find module 'minizlib' Error: Cannot fi ...

Is there a way to display a PHP error message while submitting the form asynchronously?

Utilizing phpMailer in combination with AJAX to send emails. The objective is to send the email and then showcase any error messages from submit.php on contact.php Currently, every submission displays "Message sent" even if it was not actually sent. Con ...

What are the consequences of excluding a callback in ReactJs that may lead to dysfunctionality?

<button onClick = { () => this.restart()}>Restart</button> While going through a ReactJs tutorial, I encountered a game page which featured a restart button with the code snippet mentioned above. However, when I tried to replace it with the ...

The div element is just a tad smaller in size (0.085 smaller as per the CSS calculation)

I have a div with fixed height and width of 24px with a background image, but the browser is cropping off 0.1 pixels... div { width: 24px; height: 24px; background: url(svg); } Upon inspecting the computed styles, I noticed that the height is actua ...

Utilize CSS to selectively target specific sections of a repetitive pattern within a list

I have come across a list fragment that is generated automatically and I only have the ability to adjust the CSS for it. <ul class="menu"> <li class=" menuItem1 first parent"></li> <li class=" menuItem2 parent"></li> ...

Next.js is failing to detect the @lib folder

I am currently working on a Next JS project. Within my project, I have a specific directory structure: src Within this src directory, I have subdirectories such as pages, styles, lib Inside the lib directory, there is a file named config.js This file co ...

JQuery drag and drop feature to organize interconnected lists

After looking at the JQueryUI demos, specifically this example, I am attempting to implement a feature where the sort functionality is disabled on the left list, and items from the left list are copied instead of moved. Is there a way to achieve this? If ...

JSON file not found by the system

I am currently working on a basic program that consists of 3 files: 1. An HTML file named index.html 2. A JavaScript file named app.js 3. A JSON dataset called dataset.json I am struggling to make the browser recognize the data in my program. This is ...

Retrieve various forms of information using Ajax

Currently, I am working on developing a social networking website similar to Facebook using PHP. On one of the pages titled showdetails.php, I have implemented a search bar that should display a dropdown list of user names from the database as the user typ ...

Tips for organizing list items in a grid format using CSS and HTML

In my div block, the width is not fixed. Inside the div, there is a list block with 11 items that I want to display evenly like this: ##item## ##item## ##item## ##item## ##item## ##item## ##item## ##item## ##item## ##item## ##item## I&a ...

I am unable to move HTML data to PHP

Here is my HTML code: <form action="test.php" method="get> <input type="text" name="text" /> </form> And this is my PHP code: <html> <head> <title>Result</title> </head> <body style="background: ...

Having trouble retrieving information from .pipe(map()) method

Encountering some issues with Observable handling. I have a function that returns an Observable. public getData(userId) { const data = this.execute({userId: userId}); return {event: "data.get", data: data} } private execute(input: SomeDt ...

The Art of Div Switching: Unveiling the Strategies

I have a question regarding my website. I have been working on it for some time now, but I have encountered a challenge that I am struggling to overcome. After much consideration, I am unsure of the best approach to take. The issue at hand is that I have ...

What is the process for including an item in an array within Firestore?

Can someone help me with this code snippet I'm working on: await firebase.firestore().doc(`documents/${documentData.id}`).update({ predictionHistory: firebase.firestore.FieldValue.arrayUnion(...[predictions]) }); The predictions variable is an ar ...

Only the first column of a row in Flexbox will have a line break when exceeding the

Currently, I am utilizing flex with a row direction for a set of items with fixed widths causing overflow and a horizontal scrollbar, which is the desired outcome. Nevertheless, my requirement is for the first column in these rows to be full-width, while ...

The error message popping up reads as follows: "TypeError: _this2.setState cannot

I am encountering an error that I don't quite understand. How can I resolve this issue and why is it occurring in the first place? Although I am receiving the correct response from the API, I am also getting an error immediately after making a call. ...

Executing a command efficiently in Javascript with the get method

The command that needs to be sent to the embedded device is in the form of a GET method. However, the value continuouspantiltmove: String(pt) is not being properly transmitted to the CGI script through Google Chrome, causing it to fail. Since I do not hav ...