Convert JS date time to MySQL datetime
var date;
date = new Date();
date = date.getUTCFullYear() + '-' +
('00' + (date.getUTCMonth()+1)).slice(-2) + '-' +
('00' + date.getUTCDate()).slice(-2) + ' ' +
('00' + date.getUTCHours()).slice(-2) + ':' +
('00' + date.getUTCMinutes()).slice(-2) + ':' +
('00' + date.getUTCSeconds()).slice(-2);
console.log(date);
or even shorter:
new Date().toISOString().slice(0, 19).replace('T', ' ');
Output:
2012-06-22 05:40:06
For more advanced use cases, including controlling the timezone, consider using http://momentjs.com/:
require('moment')().format('YYYY-MM-DD HH:mm:ss');
For a lightweight alternative to momentjs, consider https://github.com/taylorhakes/fecha
require('fecha').format('YYYY-MM-DD HH:mm:ss')
Convert MySql DateTime stamp into JavaScript's Date format
Some of the answers given here are either overcomplicated or just will not work (at least, not in all browsers). If you take a step back, you can see that the MySQL timestamp has each component of time in the same order as the arguments required by the Date()
constructor.
All that's needed is a very simple split on the string:
// Split timestamp into [ Y, M, D, h, m, s ]
var t = "2010-06-09 13:12:01".split(/[- :]/);
// Apply each element to the Date function
var d = new Date(Date.UTC(t[0], t[1]-1, t[2], t[3], t[4], t[5]));
console.log(d);
// -> Wed Jun 09 2010 14:12:01 GMT+0100 (BST)
Fair warning: this assumes that your MySQL server is outputting UTC dates (which is the default, and recommended if there is no timezone component of the string).
how to format mysql timestamp into mm/dd/yyyy H:i:s in javascript
Your code is missing a trailing }
. If you formatted it better, you would see this:
function formatDate(value){
if(value){
Number.prototype.padLeft = function(base,chr){
var len = (String(base || 10).length - String(this).length)+1;
return len > 0? new Array(len).join(chr || '0')+this : this;
}
var d = new Date(value),
dformat = [ (d.getMonth()+1).padLeft(),
d.getDate().padLeft(),
d.getFullYear()].join('/')+
' ' +
[ d.getHours().padLeft(),
d.getMinutes().padLeft(),
d.getSeconds().padLeft()].join(':');
return dformat;
}
}
It works fine in Firefox, now.
Note that you are defining Number.prototype.padLeft
each time you call this function. It would be better to move this out of the function body.
EDIT As per my comment, the reason this is failing for you is that the Date
object will only accept strings in certain formats. Moreover, it occurs to me that your function is just changing the format of a string: You don't really need to bother messing about with dates and, instead, just do string operations on your input:
var formatDate = function(dateString) {
// Convert 'yyyy-mm-dd hh:mm:ss' to 'mm/dd/yyyy hh:mm:ss'
return dateString.replace(/^(\d{4})-(\d{2})-(\d{2})/, '$2/$3/$1');
};
Much easier!
How to convert a Timestamp into MySQL DateTime in JavaScript?
You can pass the Date
object of JavaScript directly to MySQL. And MySQL will automatically generate the DateTime
format from that Date
object.
const date = new Date(1631514003973);
Convert MySQL date format to DD/MM/YY date format using Javascript
Hope this helps. This can be achieved in multiple ways - pure JavaScript, jQuery, Angular etc., As well it requires bit of tweaking based on your requirement. Do let me know if this helps
<script>
var myDate = new Date('2010-10-11T00:00:00+05:30');
alert((myDate.getMonth() + 1) + '/' + myDate.getDate() + '/' + myDate.getFullYear());
</script>
How to convert MySQL Timestamp to Javascript date?
Facts:
- JDBC's
java.sql.Timestamp
is a subclass ofjava.util.Date
. - JSTL has a
<fmt:formatDate>
for convertingjava.util.Date
toString
. - JavaScript
Date
constructor can take a.o. a string in ISO8601 time format.
Put together:
<c:forEach items="${results}" var="reading">
<fmt:formatDate var="time" value="${reading.time}" pattern="yyyy-MM-dd'T'HH:mm:ss" timeZone="UTC" />
var d = new Date("${time}");
// ...
</c:forEach>
Alternatively, just convert results
to JSON using a decent JSON formatter in the controller and print it as if it's a JS variable like so var data = ${data};
. See also a.o. How to access array of user defined objects within <script> in JSP?
Unrelated to the concrete problem: make sure your model is of java.util.Date
type. You shouldn't have java.sql.*
typed properties in your model. If you're using plain JDBC, just upcast ResultSet#getTimestamp()
to java.util.Date
directly. See also a.o. Handling MySQL datetimes and timestamps in Java.
Convert a mySQL date to Javascript date
Given your clarification that you cannot change the format of the incoming date, you need something like this:
var dateParts = isoFormatDateString.split("-");
var jsDate = new Date(dateParts[0], dateParts[1] - 1, dateParts[2].substr(0,2));
Original response:
Is there a reason you can't get a timestamp instead of the date string? This would be done by something like:
SELECT UNIX_TIMESTAMP(date) AS epoch_time FROM table;
Then get the epoch_time into JavaScript, and it's a simple matter of:
var myDate = new Date(epoch_time * 1000);
The multiplying by 1000 is because JavaScript takes milliseconds, and UNIX_TIMESTAMP gives seconds.
Related Topics
What Does the @ Symbol Do in JavaScript Imports
External Template in Underscore
This.Setstate Isn't Merging States as I Would Expect
How to Determine If a Number Is Odd in JavaScript
Vue V-On:Click Does Not Work on Component
React - Getting a Component from a Dom Element for Debugging
How to Detect Timeout on an Ajax (Xmlhttprequest) Call in the Browser
Moment.Js - Utc Gives Wrong Date
Chart.Js - Drawing an Arbitrary Vertical Line
Angularjs: How to Run Additional Code After Angularjs Has Rendered a Template
How to Wrap an Await/Async Try/Catch Block to Every Function
Getting a List of Associative Array Keys
How to Handle Circular Dependencies with Requirejs/Amd
JavaScript Equivalent of Jquery's Extend Method
Using Lodash .Groupby. How to Add Your Own Keys for Grouped Output
Get the Visible Height of a Div with Jquery
Can Any Desktop Browsers Detect When the Computer Resumes from Sleep