Ways to customize the datetime-local format in an HTML input field

When dealing with the HTML input of datetime type, consider the following:

Datefield:
<input type="datetime-local" data-date="" data-date-format="DD MMMM YYYY, h:mm:ss">

The script below includes important code.

$("input").val(moment().format('YYYY-MM-DD, h:mm:ss'));

$("input").on("change", function() {
this.setAttribute(
    "data-date",
    moment(this.value)
    .format( this.getAttribute("data-date-format") )
)
}).trigger("change")

I came across http://jsfiddle.net/g7mvaosL/ which allows changing the date pattern. However, when attempting to do the same with type="datetime-local", it did not work. How can this issue be resolved?

Answer №1

When using a date picker, it only returns the year, month, and day information.

console.log(this.value); //outputs 2015-08-09

Attempting to extract hours, minutes, and seconds from a date picker is not possible.

If you want to include the current time in your code, you can set it to the moment's now value.

$("input").val(moment().format('YYYY-MM-DD, h:mm:ss'));

Remember to place this line inside the on change event to ensure it updates consistently.

Adding two moments together is not feasible as it would lead to incorrect results. Instead, utilize moment.duration(). This function helps target specific time values accurately.

function nowAsDuration(){
    return moment.duration({
        hours:   moment().hour(),
        minutes: moment().minute(),
        seconds: moment().second()
    });
}

You can now use moment.add() effectively.

var a = moment(this.value);
var b = nowAsDuration();
var c = a.add(b);

For updated code, refer to http://jsfiddle.net/w7mj7feh/

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

Sending data from PHP to JavaScript using AJAX

I'm encountering an issue trying to pass data from a PHP file to a JavaScript file using echo. My PHP file contains the following code snippet: <?php ...establishing connection and retrieving list from database... for($i=0;$i<sizeOf($li ...

Property of object (TS) cannot be accessed

My question relates to a piece of TypeScript code Here is the code snippet: export function load_form_actions() { $('#step_2_form').on('ajax:before', function(data) { $('#step_2_submit_btn').hide(); $(&ap ...

Implementing Clockwise Padding with React Material-UI

Can Mui Box utilize shorthand properties for padding in a clockwise syntax? Unfortunately, this method does not work and results in a syntax error. <Box padding = {2 1 1 2}/> ...

Guide to implementing a DataTable in MVC4 UI using jQuery

Looking to set up a DataTable using jQuery similar to the one shown in this image: https://i.stack.imgur.com/DNUcd.png I'm not very comfortable with jQuery, so please be patient and avoid asking me what I've tried. I don't know how to stru ...

The positioning of the second wrapper in absolute does not match the behavior of the first wrapper

Working with CSS can be tricky, especially when dealing with nested navigation elements. I am facing an issue where the styles that work perfectly for one dropdown menu do not function as expected for subsequent nested navigations. My objective is to disp ...

Is it possible to count the number of days in between and then apply a specific class to each of those days

Here is the code snippet that I am working with: <div class="row"> <div class="test">02/12/2013</div> <div class="test">03/12/2013</div> <div class="test">04/12/2013</div> <div class="test"> ...

Tips for modifying JSON response using a function

When I call the function buildFileTree, I store its response in a constant variable called data. const data = this.buildFileTree(dataObject, 0); The value of dataObject is: const dataObject = JSON.parse(TREE_DATA); And the content of TREE_DATA is: cons ...

Creating intricate filters using React's map functionality

QUESTION HAS BEEN UPDATED. I am currently working on implementing a filter for my map, allowing users to specify which options they want to view using multiple selection boxes. However, I am encountering an issue with the page that appears after the user ...

The functionality of the WordPress Contact Form 7 Plugin becomes erratic when integrated into dynamically loaded AJAX content

I am currently facing a challenge with integrating the WordPress Contact Form 7 Plugin into a website I have built on WordPress. The theme of the site utilizes jQuery to override default link behavior and AJAX to load pages without refreshing the entire pa ...

Choose Selectize.js to auto-populate inputs

I am currently using selectize.js for my project: $("#abc").selectize({ valueField: 'name', labelField: 'name', searchField: ['name'], plugins: ['remove_button'], createOnBlur: true, ...

Updating a database seamlessly via a dropdown menu without having to refresh the entire webpage

Before we proceed, please take a look at the following code: $(document).ready(function() { $("#alternatecolor [type=button]").each(function() { $(this).on('click', function() { btnObj = $(this); rowId = $(this).attr("rowId") ...

Effortlessly Transform HTML into Plain Text Using jQuery

If I wanted to create a feature on my website where users can input text into a text area and then convert it to HTML by clicking a button, how could I achieve that? I'm looking for functionality similar to what Wordpress offers, where users can enter ...

React Native Issue: The mysterious disappearance of the 'navigation.push' object

I am trying to navigate to List.js after clicking a button in the MainMenu.js file, but I keep encountering this error: TypeError: undefined is not an object (evaluating 'navigation.push') This snippet is from my App.js file import { StatusBar ...

The issue with the search box not being correctly displayed on Google CSE using Twitter Bootstrap

Having an issue with the Google Custom Search (CSE) as it is not displaying the search box and button correctly. I am using Twitter Bootstrap v3.1.0. <script> (function() { var cx = '009077552906670546181:2ufng0dmsos'; ...

open a fresh modal by closing the existing modal using just one button

I am trying to implement a unique functionality in my bootstrap based project. I have one modal that I want to link to another modal, however, I am facing some challenges in achieving this. Currently, I am attempting to use the modal.close() and .modal(&ap ...

When attempting to use a jQuery-formatted JSON object within an <optgroup > returned via AJAX from PHP and MySQL, it appears to be incompatible with Select2

After spending an entire day attempting to create a PHP script that converts MySQL Query results into a JSON object for <optgroup> in Select2, I finally found a solution. However, when I implemented it, nothing appeared in the Select2 dropdown menu. ...

Analyzing past UTC date times results in a peculiar shift in time zones

When I receive various times in UTC from a REST application, I encounter different results. Examples include 2999-01-30T23:00:00.000Z and 1699-12-30T23:00:00.000Z. To display these times on the front end, I use new Date(date) in JavaScript to convert the ...

MongoDB can track an index in a collection using a case-insensitive regex pattern

Utilizing different indexed collections in MongoDB for queries from a straightforward search engine has been my practice. I am facing a challenge with Regex queries that need to be case insensitive, as the queried collection is not adhering to the index. ...

Utilize the cached version of jQuery if it has been recently updated, otherwise proceed with downloading the newest

Is it possible to optimize loading time for certain users by selecting a specific version of jQuery? Identify a suitable version x of jQuery, such as x = 1.4.1, and determine if the user has a more recent version y of jQuery cached. If so: if (y > x = ...

What are the solutions for resolving problems with the display and functionality of a multi-page form in Internet Explorer?

I am currently working on a form and you can view it at this link: http://jsfiddle.net/pPWr3/14/ While the form displays correctly in Chrome and Firefox, I am experiencing display and functionality issues when using Internet Explorer 9. The problems inclu ...