If you are looking for the JavaScript code for converting the format current date to MM/dd/yyyy HH:mm:ss format then you have come to the right place.
function formatDate(date) {
var d = new Date(date),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
hour = '' + d.getHours();
min = '' + d.getMinutes();
if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;
if (hour.length < 2) hour = '0' + hour;
if (min.length < 2) min = '0' + min;
var result = [year, month, day].join('-');
return result + " " + hour + ":" + min;
}
In the above Javascript function, you just need to pass the date object and it will return the desired date format.
As you can see in the code it’s very simple code you can always format date by extracting the parts of the date object and combine them using string.In above.
You can also write a generic function so that you can convert the date object to any format like below function.
function formatDate(datetimeObj, format) {
var curr_date = datetimeObj.getDate();
var curr_month = datetimeObj.getMonth();
curr_month = curr_month + 1;
var curr_year = datetimeObj.getFullYear();
var curr_min = datetimeObj.getMinutes();
var curr_hr = datetimeObj.getHours();
var curr_sc = datetimeObj.getSeconds();
if (curr_month.toString().length == 1)
curr_month = '0' + curr_month;
if (curr_date.toString().length == 1)
curr_date = '0' + curr_date;
if (curr_hr.toString().length == 1)
curr_hr = '0' + curr_hr;
if (curr_min.toString().length == 1)
curr_min = '0' + curr_min;
if (format == 1)//dd-mm-yyyy
{
return curr_date + "-" + curr_month + "-" + curr_year;
}
else if (format == 2)//yyyy-mm-dd
{
return curr_year + "-" + curr_month + "-" + curr_date;
}
else if (format == 3)//dd/mm/yyyy
{
return curr_date + "/" + curr_month + "/" + curr_year;
}
else if (format == 4)// MM/dd/yyyy HH:mm:ss
{
return curr_month + "/" + curr_date + "/" + curr_year + " " + curr_hr + ":" + curr_min + ":" + curr_sc;
}
}
The post [Solved]-How to format Date Object in MM/DD/YYYY HH:MM:SS format using JavaScript ? appeared first on Software Development | Programming Tutorials.
Read More Articles
- [Simple Way]-Cascading DropDownList in Asp.Net Mvc Using Jquery Ajax
- jQuery Ajax GET Example with Parameters
- How to Pass Parameters in AJAX POST?| JQuery Ajax Post Json Example
- [Simple Way]-How to get data from database using JQuery Ajax in asp net MVC
- How to add, edit and delete rows of an HTML table with Jquery?
- Registration form with image upload in MVC using jquery Ajax
- How to make an Inline editable table in MVC using jquery?
- Insert Update Delete Using Jquery Ajax and Modal Popup in Mvc
- [Solved]-How to Upload pdf file using jquery MVC?
- Dynamically creating graphs with jQuery
- How to code a 5-state toggle link
- RequireJS: How do I unload previously loaded javascript file? Aka Exclusive Dependancies? Or maybe Reset RequireJS?
- Draw line over divs
- Align inputs in different td horizontally
- How to Update a Class in HTML given a new Firebase response?
- How do I apply encodeURIComponent() before submit?
- How to set visible posts by js?
- Using <iframe> to add one HTML page to another, how to give effects on first page
- Assigning ajax call return value to an var with jquery
- Getting all POST from clone form elements
- Dynamic iframe height depending on hide/show
- Rotating chevrons with JQuery
- setTimeout function associated with a event
- Jquery validation not working second time
- JqueryUI DatePicker parseDate comparison
- jQuery.find() IE7 bug?
- Using jQuery, how can I ajax load text into multiple .classes rather than #id's?
- offset().left, offsetLeft, offset.left, what's the difference? why not use the pure js offsetLeft instead of the jQuery way?
- How to render images as dropdown lists using ajax and json?
- jquery: click callback is called even if button is disabled?
- How to create a valid string using a function for jqGrid editoptions value?
- Add delay before .hide() w/jQuery
- Image from an array HTML Javascript
- SignalR connection get warning - Synchronous XMLHttpRequest on the main thread is deprecated
- Dynamically loading content with Ajax
- jQuery: only run the callback function once after all the event changes
- jquery compare data in same row, if correct show content of third data in row
- Uncaught ReferenceError: is not defined onclick
- jQuery: easy adaptable tooltips without the use of images and free for commercial uses
- .unwrap() doesn't work after .append().load()
- javascript/jquery remove relative path from url
- Background worker for jQuery Mobile App
- Toggle navbar color on window scroll bootstrap + jquery
- Galleria Galleries Not Loading Correctly After Infinite Scroll
- How to combine bxslider and lightbox?
- Need equal height columns to resize with dynamic content
- Ajax file upload with preview
- How to put image inside a circle with Raphael Js
- required with input and javascript not working
- how to append with content and afterAppending function in jquery
- Shared service: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked
- jQuery Disable Submit -- AND Post Value?
- refresh input after ajax submit form
- Get JSON url from textbox?
- Javascript toggle menu -issue with sub-menues
- How to trigger F5 key and reload page manually with full cache use
- Displaying something over an inline PDF in Internet Explorer
- Convert Canvas to image then download
- Twitter TypeAhead show all results programmatically
- clone primefaces components with jquery
- jQuery noconflict, bootstrap and requirejs
- Two same function working differently
- can we get id from multiple elements having same name using serialize array
- How to execute a function after scrolling (jquery)
- jQuery: disable click during animation
- Adding dynamically retrieved content to a jQuery Mobile PHP MVC to the jQuery object
- autocomplete label not displaying data
- Waiting in JavaScript beyond wrapping everything in setTimeout
- jquery post method for form submit always takes 1st record even on selecting other records
- Check if value exists in JSON
- Multiple JSON objects
- How to disable changing GoJS diagram after page refreshing?
- Can't show the element when its class or id contains dots
- I want to send two parameters on one ajax request
- Animating form size
- How to retrieve objects from sessionStorage?
- Using JQuery to select the Last Select Value?
- Count elements with certain class exists after a click action
- Ajax call to MVC Controller return "NOT FOUND"
- How to get width in specified units (pt, ex, etc.)
- jQuery- Add text to same line of each radio input
- Getting error while sending ajax call [internal server error 500]
- Pass rails form params into jQuery
- How to use nested json values in c3 chart | Jquery
- How to dynamically clone a tab with Jquery
- CSS transition from fixed to absolute with change in top not working
- Insert data into MySQL Database using javascript/AJAX
- pickadate() function is not working on cloned elements
- How to dynamically show/hide Rails form fields using CoffeeScript and JQuery?
- Push to an array only if it isn't present already
- Optimal method for parsing a keyed JSON object
- Query textfields characters length count with "for -> keyup"
- ajaxQueue loading icon
- select random id from set of elements with the same class
- Handlebar incrementing variable
- Uncaught TypeError: Cannot read property '_setter' of undefined
- Jquery : To redirect from one page to another page
- Calling a function within a jQuery plug-in
- Implementing Drag n Drop using JQuery
- Code Mirror overlay applied
- asp.net: How to access repeater generated elements using javascript or jquery?
- Why does chrome try to load the unminified version of jQuery when including the minified version?
- Ajax load - several containers
- How to make one element get hovered when hover on other element
- Prevent first form submit when submit second from
- How to add a wait time before hover function is executed
- How to pass Array to MVC Controller with Jquery?
- Javascript interaction with Android's Webview
- How to show submenu which contains specific class
- Use jQuery load with fadeIn technique
- Changing parent css on child hover
- Stop the current video playing when user play another video?
- FadeIn one element and fadeOut all others
- Call function created in view using javascript in the same view
- Change dropbtn text with value of clicked option in the dropdown-content
- Change ::selection when button is clicked
- Exclude array from array in jQuery
- Replace cookie value to space character using jQuery
- Hide links from Google via JavaScript
- jQuery show multiple image thumbnail before upload
- Is it just me, or does setting a modal on a dialog after it is created just not work?
- Disabling the future 7days in DATETIMEPICKER javascript
- Ajax call returning 0 as response in mobile
- Change text of canvas without using canvas.getActiveObject() method
- Knockout.js Change form value based on another form value
- Issue while calling a Web Service through JQuery
- DropDownList SelectedIndexChanged doesn't run when original value is reset on the client
- How to fade out neighbors of a hovered link?
- Common function for validation using jquery
- jQuery multidimensional array definition
- Select value of property by using another property
- Delay on jquery keyup?
- Custom confirm box that has some functionality to it with window close event
- jQuery UI Not being loaded properly? Dialog method not found
- jQuery AJAX auto refresh values
- Creating Heart Rate Monitor Chart using js
- jQuery: Inaccuracy with scrollLeft when scaled
- Rails link_to with ajax remote true not updating view
- Making JSON Feed Work Server to Server
- Targeting Dynamic Div
- tooltip doesn't work in a table cell
- Jquery scrolltop triggering a function between two points?
- JSON keys with decimal points not in order
- How to add additional event handler in jQuery or plain javascript?
- jQuery 1.4.4 error "q.replace is not a function"
- jQuery datetimepicker validation - Timepicker UI
- merging 3 click functions into 1 jquery
- $.on("mouseenter") lags my website when I have a lot of Dynamically generated div tags
- How can Slow down scroll to top event by jQuery animate
- CSS full page height content
- JavaScript .scrollIntoView({behavior: "smooth"}); alternative is not working
- Dynamically change jquery contextmenu
- Show elements after specific Class
- jsZip opened png image, POST it into server with ajax
- jQuery fadeIn elements one at a time with onClick
- How to find the mouse position inside an element
- Animate background image from bottom to top, continuous repeat jQuery
- Django ajax comments using Jquery?
- rails 3 javascript fine coffeescript referenceerror (class) is not defined
- jQuery and asp.net not playing nice together