let isoDate = '2018-01-01T18:00:00Z';
My goal is to extract the time of 18:00 from the given ISO date using any available method, including moment.js.
let isoDate = '2018-01-01T18:00:00Z';
My goal is to extract the time of 18:00 from the given ISO date using any available method, including moment.js.
Vanilla Javascript example showcasing how to work with dates and times.
const dateObj = new Date('2018-01-01T18:00:00Z');
const hour = dateObj.getUTCHours();
const minute = dateObj.getUTCMinutes();
console.log(hour, minute);
console.log(`${hour}:${minute}`); // e.g: 15:38
This code makes use of the built-in Date
object in JavaScript. If you prefer not to rely on external libraries for this task, give it a try.
For further information, visit: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
To find that exact section, you can utilize regular expressions.
const dateTime = '2022-12-31T23:59:59Z';
const timeResult = dateTime.match(/\d\d:\d\d/);
console.log(timeResult[0]);
Looking for a simple solution in JavaScript? Here's a one-liner to extract the time from a date string:
console.log("2018-01-01T18:00:00Z".replace(/^[^:]*([0-2]\d:[0-5]\d).*$/, "$1"));
If you have a Date object instead of a string, you can easily convert it using the toISOString
method like this:
let date = new Date('2018-01-01T18:00:00Z');
console.log(date.toISOString().replace(/^[^:]*([0-2]\d:[0-5]\d).*$/, "$1"));
If you're looking to achieve this, I recommend utilizing the momentjs library.
By default, moment will parse and display in local time. To parse or display a moment in UTC, simply use moment.utc() instead of moment()
var t = moment.utc("2018-01-01T18:00:00Z").format("HH:mm")
console.log(t)
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="660b090b030812265448575f4855">[email protected]</a>/moment.min.js"></script>
When I needed to extract the time from a date, this method proved to be effective:
let isoDate= '2020-09-28T15:27:15+05:30';
let result = isoDate.match(/\d\d:\d\d/);
console.log(result[0]);
The above code will only display the time portion of the isoDate, which is:
15:27
One way to extract specific information using regular expressions is by utilizing regex groups:
const ISODateFormat = '2021-07-19T13:04:20.602Z';
const regex = /([0-9]{4}-[0-9]{2}-[0-9]{2})?.([:0-9]+)/;
console.log(ISODateFormat.match(regex));
// the expected result should be: Array ["2021-07-19T13:04:20", "2021-07-19","13:04:20"]
An ISO date format consists of either YYYY-MM-DDTHH:mm:ss.sssZ
or ±YYYYYY-MM-DDTHH:mm:ss.sssZ
, where the letter T
signifies the time portion. To extract the date and time separately, first split the string based on the T
character, with the initial half representing the date and the latter half indicating the time. Finally, split the time section using the period (.
) to isolate the HH:MM:SS
part:
const dateTime = "2023-11-10T15:25:14.416+0000";
const [date, time] = dateTime.split('T');
const timeHHMMSS = time.split('.')[0];
console.log(`Date is ${date}`); // Date is: 2023-11-10
console.log(`Time is ${timeHHMMSS}`); // Time is: 15:25:14
In my app, I have a Header.tsx component that needs to be accessible on all pages and a Home.tsx component where most of the content resides. The Home.tsx component includes an intersectionObserver that utilizes the useContext hook (called homeLinks) to p ...
Is there a way to make the CSS margin: top; on my HTML main_content element relative to the browser window? I want the main_content to always stay at the bottom of the browser window. How can I achieve this? I attempted the following code, but it didn&apo ...
const mysql = require('mysql'); const inquirer = require('inquirer'); const connection = mysql.createConnection({ host: "localhost", port: 8889, user: "root", password: "root", database: "bamazon" }) connection.conn ...
I am facing an issue with a web page that includes a scriptlet like this: <div id="flash_chart"> <%=content_data['report_text']%> </div> The variable content_data['report_text'] contains a lengthy string ...
I am struggling to combine the outcomes of two jQuery AJAX requests. Despite reviewing similar questions here, none seem to provide a solution. Each ajax call (2 in total) has a success function that calls the createStatusView function and passes it the ...
Would it be feasible to asynchronously load a column of data in the MUI DataGrid after the table is displayed on the screen? Retrieving this additional data from the database is time-consuming, so I aim to have it appear once the table has fully loaded. T ...
I have created a dynamic form with three interconnected select elements. The first select element is populated with data fetched from a MySQL database using PHP. The second select element is populated based on the selection made in the first one, triggered ...
I am currently using Handlebars to display data retrieved from a MySQL query. The route is set up as shown below: var query = "SELECT col1, col2, col3 FROM table WHERE section >= " + start + " AND section <= " + end + " ORDER BY col1 ASC"; connecti ...
When using the onchange function, I am able to open a socket and emit/fetch data successfully. However, a new socket is opened on any event. I need to find a way to emit data from the same socket ID without opening a new socket each time. Could you pleas ...
I am currently working on designing my modules in such a way that they don't need to be required multiple times. In my approach, I am passing arguments from the main app.js file to all of my modules. One of the modules I have is for user login and it ...
Currently, I am in the process of writing unit tests for a function that requires fetching values from the DOM for processing. getProducts: function() { //Creating query data var queryData = {}; var location = this.$('#location').val(); ...
let address = 'http://sub.domain2.net/contact/'; if (['https://sub.domain1.com/', 'http://sub.domain2.net/'].includes(address)) { console.log('match'); } else { console.log('no match'); } Here, it ...
I am facing an issue with retrieving the value of the status property from an object in my code. Below is a snippet of what I have tried: console.log("Resource.query()"); console.log(Resource.query()); console.log("Resource.query().status"); console.log(R ...
Looking to showcase a list of products categorized and fetched from an API? Check out the code snippet below: const API = "https://dummyjson.com/products"; const ProductsList = () => { const { cate } = useParams(); //retrieving category fro ...
In the process of creating my inaugural project featuring a collection of images, I wanted to include a filter/search bar at the top. This bar would dynamically filter the displayed pictures based on user input. For example, typing "Aatrox" into the search ...
I'm facing a basic issue that I can't seem to solve - my code isn't working as expected: <article id="desktop"> <h3>Content: </h3> <ul> <li ng-repeat="x in storage"> name: {{x.name}} ...
Recently, I've been experimenting with a small project involving draggable divs. However, the code I've written doesn't seem to be functioning properly, causing JQuery to become unresponsive. Is there an alternative method that is simple an ...
I am looking to adjust the font size based on the value within the span element. The numbers in the class name may vary. Issue: using text() retrieves all values (e.g. 50020) I want to incorporate each() and $this in some way. How can I do this? Thank ...
Currently, I am integrating the community js library version of jsplumb with my Angular 5 application (Angular CLI: 1.6.1). Upon my initial build without any modifications to tsconfig.json, I encountered the following error: ERROR in src/app/jsplumb/jspl ...
I am currently using MaterialTable imported from "material-table". import MaterialTable from "material-table" I am attempting to make the 'lookup' for an editable table dynamic. My goal is to have a drop-down with edit options when I make change ...