Unix to datetime object using Javascript - javascript

I am trying to convert a unix time stamp to a datetime object using javascript but am getting a strange output.
The unix timestamps I'm using are 1420243200000 and 1420272000000. My javascript code looks like this:
function timeConverter(UNIX_timestamp){
// var a = new Date(UNIX_timestamp*1000);
// var year = a.getFullYear();
// var month = a.getMonth()+1;
// var date = a.getDate();
// var hour = a.getHours();
// var min = "0" + a.getMinutes();
// var sec = "0" + a.getSeconds();
// var time = date + ' ' + month + ' ' + year + ' ' + hour + ':' + min.substr(-2) + ':' + sec.substr(-2) ;
// return time;
var myDate = new Date( UNIX_timestamp *1000);
time = myDate.toLocaleString();
return time;
}
Neither the commented or uncommented attempts produce the correct date. I keep getting 9/18/46975, 6:00:00 PM and 8/17/46976, 2:00:00 AMas the answers and I can't figure out what's going wrong.

Your timestamp appears to already be in milliseconds. Don't multiply with 1000.
Calling it "UNIX_timestamp" is misleading. Unix timestamp is seconds elapsed since epoch. Timestamps from JS functions (like Date.now() and +new Date()) are milliseconds elapsed since epoch.

try myDate = new Date(1420243200000);
From the documentation https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
Call the constructor new Date(value);. Where value is "Integer value representing the number of milliseconds since 1 January 1970 00:00:00 UTC (Unix Epoch)."

Related

Javascript subtract one day from "yyyy-mm-ss" string IN UTC TIMEZONE

I have a string for a UTC date var latestDate='2020-11-17' , and I'm trying to get the previous days date from this string into a new variable var subtractedDate;.
So my goal is to get subtractedDate=2020-11-16
var latestDate='2020-11-17';
//convert to iso date string
var dateStr = new Date(latestDate).toISOString();
console.log('dateStr=', dateStr);
//subtract a day
//ERROR OCCURS HERE, has trouble running // var subtractedDate = dateStr.setDate(('2020-11-17T00:00:00.000Z').getDate()-1);, something with how I have '2020-11-17T00:00:00.000Z' formatted?
var subtractedDate = dateStr.setDate(dateStr.getDate()-1);
console.log('subtractedDate = ', subtractedDate);
I am trying to use ('2020-11-17T00:00:00.000Z').getDate()-1 to subtract a day from the datetimestamp but it causes an error saying Uncaught TypeError: dateStr.getDate is not a function
We should be able to use Date.parse to get the number of milliseconds since January 1, 1970, 00:00:00 UTC, then subtract 1 days worth of milliseconds (246060*1000) to get the unix time one day earlier.
We can then use Date.toLocaleTimeString to format it.
const latestDate='2020-11-17';
// Get the number of milliseconds since 1970-1-1, then subtract 1 day (24*60*60*1000 milliseconds)
const dt = new Date(Date.parse(latestDate) - 24*60*60*1000);
// Format an ISO-8601 date in the UTC timezone
const subtractedDate = dt.toLocaleDateString('sv', { timeZone: 'UTC' });
console.log({ latestDate, subtractedDate })
Please try as follows.
dateStr.setDate(dateStr.getDate()-1);
var dateStr = new Date();
var month = dateStr.getUTCMonth() + 1; //months from 1-12
var day = dateStr.getUTCDate();
var year = dateStr.getUTCFullYear();
newdate = year + "/" + month + "/" + day;

Timestamp calculated from the current time instead the source date

I want to add 30 days to a Date (including the timestamp), however, the timestamp is being calculated from the execution time of the script instead of the source data (loadStartDateTime).
I created a new date object and then set the date (purge_date = loadStartDateTime + 30days).
I saw an example doing some math with the dates, should I make the calculations of the timestamp separately?
PURGEDATE = (function (loadTime) {
var loadDate = new Date(loadTime);
var purge_date = new Date();
purge_date.setDate(loadDate.getDate()+30);
var month = purge_date.getMonth() + 1;
var mm = month < 10 ? "0" + month : month;
var day = purge_date.getDate();
var dd = day < 10 ? "0" + day : day;
var hours = purge_date.getHours() < 10 ? "0" + purge_date.getHours() : purge_date.getHours();
var minutes = purge_date.getMinutes() < 10 ? "0" + purge_date.getMinutes() : purge_date.getMinutes();
var seconds = purge_date.getSeconds() < 10 ? "0" + purge_date.getSeconds() : purge_date.getSeconds();
var time = hours + ":" + minutes + ":" + seconds;
var yyyy = purge_date.getFullYear();
return mm + "/" + dd + "/" + yyyy + time;
})(LoadStartDateTime)
The Result:
loadStartDateTime | PurgeDate
8/7/2018 5:55:45 PM | 09/06/2018 10:28:49
8/7/2018 5:58:10 PM | 09/06/2018 10:28:49
I saw an example doing some math with the dates, should I make the calculations of the timestamp separately?
Thank you~
After further investigation I realized that:
The Date object’s constructor is ISO 8601
When I use getDate() I do not provide the timezone explicitly.
This causes the timestamp to be 00:00:00 local time, so I should use getTime() method instead to get the timestamp. Since in JavaScript a timestamp is the number of milliseconds, a simple way to get it done is to send the timestamp value in the Date constructor. To calculate 30 days measured in timestamp:
30 * 24 * 60 * 60 * 1000
Finally, sum both values and send the result as a param in the constructor:
For example:
loadStartDateTime = new Date('8/7/2018 5:55:45 PM');
test_date = loadStartDateTime.getTime() + (30 * 24 * 60 * 60 * 1000);
test_date = new Date(test_date);
and then can continue with the Date Formatting.
I found the solution combining the answers from ISO 8601 date format - Add day with javascript and Add 30 days to date (mm/dd/yy). This guide "The Definitive Guide to DateTime Manipulation" helped to find out when I was wrong by understanding more about DateTime Manipulation.

Formatting seconds duration into DD:HH:mm format by using moment.js

I'm trying to count calculate a duration from seconds into a DD-HH-mm format.
My javascript code:
var seconds = 120;
var result = moment.utc(seconds*1000).format('DD:HH:mm');
My code should return something like this: 00:00:02 (DD:HH:MM) but it returns that: 01:00:02 (DD:HH:MM)!
I'm sure that's because of my local time, but how to fix the 1 hour interval in general?
moment.utc creates a moment.js object with a timezone set to GMT/UTC. When using a date for a duration, you need to allow for the date starting from 1, not zero. Also, if the duration is 32 days or longer, the "days" will reset to 1.
Moment.js also has durations, however, they don't support formatting other than "humanize" or converting to particular units.
If your durations are less than 32 days, you can use a date starting from 1 January in any year provided you deal with the day number not being zero indexed (i.e. subtract 1 from the day).
So getting your required format with moment.js is a bit more work than just formatting a date, you'll need a sequence of steps so consider writing a function. A plain JS function is no more work than a moment one in this case, it will handle durations 32 days or longer and is not affected by Date vagaries like daylight saving and timezones.
var secs = 120;
// Using a duration
var m = moment.duration(secs * 1000);
console.log(m);
console.log(m.humanize());
console.log(m.asMinutes());
// Using a date and seconds value
var x = moment.utc(secs*1000);
// Generated date
console.log(x.format());
// Get the days separately
var dayNum = x.format('D') - 1;
// Format with hours and minutes
console.log(('0'+dayNum).slice(-2) + x.format(':HH:mm'))
// Function using moment.js
function myFormat(secs) {
var x = moment.utc(secs*1000);
var dayNum = x.format('D') - 1;
return ('0'+dayNum).slice(-2) + x.format(':HH:mm');
}
// Function without using a Date
function duration(secs) {
function z(n){return ('0'+n).slice(-2)}
return z((secs/8.64e4|0))
+ ':' + z((secs%8.64e4)/3.6e3|0)
+ ':' + z((secs%3.6e3)/60|0)
// + ':' + z(secs%60);
}
console.log(duration(secs));
// Some other tests
var min = 60;
var hr = 60*min; // 3,600
var day = 24*hr; // 86,400
//2 days 17 hours 53 minutes and 08 seconds
var d = 2*day + 17*hr + 53*min + 8;
//0 days 1 hour 2 minutes and 1 second
var e = 0*day + 1*hr + 2*min + 1;
// 48 days 21 hours 15 minutes
var f = 48*day + 21*hr + 15*min;
[120, d, e, f].forEach(function(d) {
console.log(d + ' seconds');
console.log('Plain js: ' + duration(d));
console.log('Moment fn: ' + myFormat(d));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.1/moment.min.js"></script>
The format seems ambiguous, I think many would interpret it as HH:mm:ss rather than DD:HH:mm.

Handling dates (formatting and timezones) in javascript

The use case is that I am getting the date in millis (from epoch) through an ajax call, which now needs to be interpreted in the javascript. This corresponded to some point of time in UTC.
Now I need to display this date in PST, as that is the only relevant time zone for the users irrespective of where they are opening the page from.
Also, I need to show it in a different format like 'yyyy-mm-dd HH:mm' rather than the default Locale string.
Can someone please tell me, how I can do that.
Create a new date using the UNIX milliseconds value plus the offset to PST, then create your formatted string using getUTC series of calls.
Moment.js is a pretty nice library for this type of thing.
I believe the timezones are determined by the user's timezone setting when you use the new Date() function.
var myDateTime = 1312312732923;
var myDate = new Date(myDateTime);
var myFormattedDate = myDate.getFullYear() + "-" + (myDate.getMonth()+1) + "-" + myDate.getDay();
http://www.w3schools.com/jsref/jsref_obj_date.asp
JavaScript has now way to set the timezone that you want to display something in. I've used Flot for a library for charting and their suggested solution is to use the getUTC methods when displaying the dates. That means that your server code can't send the standard millis from epoch (since that would display GMT time), but a small adjustment on the server will make your dates display correctly on the client.
To read about the problem, see http://flot.googlecode.com/svn/trunk/API.txt, and look for the heading "Time series data"
Use the Date object: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date
Javascript's Date object works with milliseconds rather than seconds, so you'll have to multiply a UNIX timestamp by 1000:
var myDate = new Date(unix_timestamp * 1000);
Then, you can use the local-specific Date object to do whatever you'd like:
var output = myDate .getHours() + ':';
output += myDate .getMinutes() + ':';
output += myDate .getSeconds();
alert(output);
EDIT Ah, missed the part about using PST always, regardless of locale. unix_timesamp again is the epoch/UNIX timestamp you're getting from the server:
Try it here: http://jsfiddle.net/46PYZ/
// set to the UTC offset for the target timezone, PST = UTC - 8
var target_offset = -8;
// create a Date object
var myDate = new Date();
// add local time zone offset to get UTC time in msec
var utc_milliseconds = (unix_timesamp * 1000) + (myDate .getTimezoneOffset() * 60000);
// set the time using the calculated UTC timestamp
myDate.setTime(utc_milliseconds + (3600000 * target_offset));
// now build the yyyy-mm-dd HH:mm format
var output = myDate.getFullYear() + '-';
var month = myDate.getMonth() + 1;
output += (month < 10 ? '0' + month : month) + '-';
output += myDate.getDate() + ' ';
var hours = myDate.getHours() + 1;
output += (hours < 10 ? '0' + hours : hours) + ':';
var minutes= myDate.getMinutes() + 1;
output += (minutes< 10 ? '0' + minutes : minutes);

Convert JS date time to MySQL datetime

Does anyone know how to convert JS dateTime to MySQL datetime? Also is there a way to add a specific number of minutes to JS datetime and then pass it 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')
I think the solution can be less clunky by using method toISOString(), it has a wide browser compatibility.
So your expression will be a one-liner:
new Date().toISOString().slice(0, 19).replace('T', ' ');
The generated output:
"2017-06-29 17:54:04"
While JS does possess enough basic tools to do this, it's pretty clunky.
/**
* You first need to create a formatting function to pad numbers to two digits…
**/
function twoDigits(d) {
if(0 <= d && d < 10) return "0" + d.toString();
if(-10 < d && d < 0) return "-0" + (-1*d).toString();
return d.toString();
}
/**
* …and then create the method to output the date string as desired.
* Some people hate using prototypes this way, but if you are going
* to apply this to more than one Date object, having it as a prototype
* makes sense.
**/
Date.prototype.toMysqlFormat = function() {
return this.getUTCFullYear() + "-" + twoDigits(1 + this.getUTCMonth()) + "-" + twoDigits(this.getUTCDate()) + " " + twoDigits(this.getUTCHours()) + ":" + twoDigits(this.getUTCMinutes()) + ":" + twoDigits(this.getUTCSeconds());
};
JS time value for MySQL
var datetime = new Date().toLocaleString();
OR
const DATE_FORMATER = require( 'dateformat' );
var datetime = DATE_FORMATER( new Date(), "yyyy-mm-dd HH:MM:ss" );
OR
const MOMENT= require( 'moment' );
let datetime = MOMENT().format( 'YYYY-MM-DD HH:mm:ss.000' );
you can send this in params its will work.
For arbitrary date string,
// Your default date object
var starttime = new Date();
// Get the iso time (GMT 0 == UTC 0)
var isotime = new Date((new Date(starttime)).toISOString() );
// getTime() is the unix time value, in milliseconds.
// getTimezoneOffset() is UTC time and local time in minutes.
// 60000 = 60*1000 converts getTimezoneOffset() from minutes to milliseconds.
var fixedtime = new Date(isotime.getTime()-(starttime.getTimezoneOffset()*60000));
// toISOString() is always 24 characters long: YYYY-MM-DDTHH:mm:ss.sssZ.
// .slice(0, 19) removes the last 5 chars, ".sssZ",which is (UTC offset).
// .replace('T', ' ') removes the pad between the date and time.
var formatedMysqlString = fixedtime.toISOString().slice(0, 19).replace('T', ' ');
console.log( formatedMysqlString );
Or a single line solution,
var formatedMysqlString = (new Date ((new Date((new Date(new Date())).toISOString() )).getTime() - ((new Date()).getTimezoneOffset()*60000))).toISOString().slice(0, 19).replace('T', ' ');
console.log( formatedMysqlString );
This solution also works for Node.js when using Timestamp in mysql.
#Gajus Kuizinas's first answer seems to modify mozilla's toISOString prototype
new Date().toISOString().slice(0, 10)+" "+new Date().toLocaleTimeString('en-GB');
The easiest correct way to convert JS Date to SQL datetime format that occur to me is this one. It correctly handles timezone offset.
const toSqlDatetime = (inputDate) => {
const date = new Date(inputDate)
const dateWithOffest = new Date(date.getTime() - (date.getTimezoneOffset() * 60000))
return dateWithOffest
.toISOString()
.slice(0, 19)
.replace('T', ' ')
}
toSqlDatetime(new Date()) // 2019-08-07 11:58:57
toSqlDatetime(new Date('2016-6-23 1:54:16')) // 2016-06-23 01:54:16
Beware that #Paulo Roberto answer will produce incorrect results at the turn on new day (i can't leave comments). For example:
var d = new Date('2016-6-23 1:54:16'),
finalDate = d.toISOString().split('T')[0]+' '+d.toTimeString().split(' ')[0];
console.log(finalDate); // 2016-06-22 01:54:16
We've got 22 June instead of 23!
The venerable DateJS library has a formatting routine (it overrides ".toString()"). You could also do one yourself pretty easily because the "Date" methods give you all the numbers you need.
The short version:
// JavaScript timestamps need to be converted to UTC time to match MySQL
// MySQL formatted UTC timestamp +30 minutes
let d = new Date()
let mySqlTimestamp = new Date(
d.getFullYear(),
d.getMonth(),
d.getDate(),
d.getHours(),
(d.getMinutes() + 30), // add 30 minutes
d.getSeconds(),
d.getMilliseconds()
).toISOString().slice(0, 19).replace('T', ' ')
console.log("MySQL formatted UTC timestamp: " + mySqlTimestamp)
UTC time is generally the best option for storing timestamps in MySQL. If you don't have root access, then run set time_zone = '+00:00' at the start of your connection.
Display a timestamp in a specific time zone in MySQL with the method convert_tz.
select convert_tz(now(), 'SYSTEM', 'America/Los_Angeles');
JavaScript timestamps are based on your device's clock and include the time zone. Before sending any timestamps generated from JavaScript, you should convert them to UTC time. JavaScript has a method called toISOString() which formats a JavaScript timestamp to look similar to MySQL timestamp and converts the timestamp to UTC time. The final cleanup takes place with slice and replace.
let timestmap = new Date()
timestmap.toISOString().slice(0, 19).replace('T', ' ')
Long version to show what is happening:
// JavaScript timestamps need to be converted to UTC time to match MySQL
// local timezone provided by user's device
let d = new Date()
console.log("JavaScript timestamp: " + d.toLocaleString())
// add 30 minutes
let add30Minutes = new Date(
d.getFullYear(),
d.getMonth(),
d.getDate(),
d.getHours(),
(d.getMinutes() + 30), // add 30 minutes
d.getSeconds(),
d.getMilliseconds()
)
console.log("Add 30 mins: " + add30Minutes.toLocaleString())
// ISO formatted UTC timestamp
// timezone is always zero UTC offset, as denoted by the suffix "Z"
let isoString = add30Minutes.toISOString()
console.log("ISO formatted UTC timestamp: " + isoString)
// MySQL formatted UTC timestamp: YYYY-MM-DD HH:MM:SS
let mySqlTimestamp = isoString.slice(0, 19).replace('T', ' ')
console.log("MySQL formatted UTC timestamp: " + mySqlTimestamp)
This is by far the easiest way I can think of
new Date().toISOString().slice(0, 19).replace("T", " ")
Full workaround (to mantain the timezone) using #Gajus answer concept:
var d = new Date(),
finalDate = d.toISOString().split('T')[0]+' '+d.toTimeString().split(' ')[0];
console.log(finalDate); //2018-09-28 16:19:34 --example output
I have given simple JavaScript date format examples please check the bellow code
var data = new Date($.now()); // without jquery remove this $.now()
console.log(data)// Thu Jun 23 2016 15:48:24 GMT+0530 (IST)
var d = new Date,
dformat = [d.getFullYear() ,d.getMonth()+1,
d.getDate()
].join('-')+' '+
[d.getHours(),
d.getMinutes(),
d.getSeconds()].join(':');
console.log(dformat) //2016-6-23 15:54:16
Using momentjs
var date = moment().format('YYYY-MM-DD H:mm:ss');
console.log(date) // 2016-06-23 15:59:08
Example please check https://jsfiddle.net/sjy3vjwm/2/
var _t = new Date();
if you want UTC format simply
_t.toLocaleString('indian', { timeZone: 'UTC' }).replace(/(\w+)\/(\w+)\/(\w+), (\w+)/, '$3-$2-$1 $4');
or
_t.toISOString().slice(0, 19).replace('T', ' ');
and if want in specific timezone then
_t.toLocaleString('indian', { timeZone: 'asia/kolkata' }).replace(/(\w+)\/(\w+)\/(\w+), (\w+)/, '$3-$2-$1 $4');
Using toJSON() date function as below:
var sqlDatetime = new Date(new Date().getTime() - new Date().getTimezoneOffset() * 60 * 1000).toJSON().slice(0, 19).replace('T', ' ');
console.log(sqlDatetime);
Datetime in a different time zone
This uses #Gayus solution using the format outputted from toISOString() but it adjusts the minutes to account for the time zone.
Final format: 2022-03-01 13:32:51
let ts = new Date();
ts.setMinutes(ts.getMinutes() - ts.getTimezoneOffset());
console.log(ts.toISOString().slice(0, 19).replace('T', ' '));
I am surprised that no one mention the Swedish date time format for javascript yet.
the BCP 47 language tag for the Swedish language is sv-SE that you can use for the new Date "locale" parameter.
I am not saying it is a good practice, but it works.
console.log(new Date().toLocaleString([['sv-SE']])) //2022-09-10 17:02:39
A simple solution is send a timestamp to MySQL and let it do the conversion. Javascript uses timestamps in milliseconds whereas MySQL expects them to be in seconds - so a division by 1000 is needed:
// Current date / time as a timestamp:
let jsTimestamp = Date.now();
// **OR** a specific date / time as a timestamp:
jsTimestamp = new Date("2020-11-17 16:34:59").getTime();
// Adding 30 minutes (to answer the second part of the question):
jsTimestamp += 30 * 1000;
// Example query converting Javascript timestamp into a MySQL date
let sql = 'SELECT FROM_UNIXTIME(' + jsTimestamp + ' / 1000) AS mysql_date_time';
I needed a function to return the sql timestamp format in javascript form a selective timezone
<script>
console.log(getTimestamp("Europe/Amsterdam")); // Europe/Amsterdam
console.log(getTimestamp()); // UTC
function getTimestamp(timezone) {
if (timezone) {
var dateObject = new Date().toLocaleString("nl-NL", { // it will parse with the timeZone element, not this one
timeZone: timezone, // timezone eg "Europe/Amsterdam" or "UTC"
month: "2-digit",
day: "2-digit",
year: "numeric",
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
});
let [dateRaw, timeRaw] = dateObject.split(" ");
let [day, month, year] = dateRaw.split("-");
var timestamp = year + "-" + month + "-" + day + " " + timeRaw;
}else{
// UTC from #Gajus, 95% faster then the above
timestamp = new Date().toISOString().slice(0, 19).replace("T", " ");
}
return timestamp; // YYYY-MM-DD HH:MI:SS
}
</script>
If you are using Date-fns then the functionality can be achived easily using format function.
const format = require("date-fns/format");
const date = new Date();
const formattedDate = format(date, "yyyy-MM-dd HH:mm:ss")
This is the easiest way -
new Date().toISOString().slice(0, 19).replace("T", " ")
I'm using this long time and it's very helpful for me, use as you like
Date.prototype.date=function() {
return this.getFullYear()+'-'+String(this.getMonth()+1).padStart(2, '0')+'-'+String(this.getDate()).padStart(2, '0')
}
Date.prototype.time=function() {
return String(this.getHours()).padStart(2, '0')+':'+String(this.getMinutes()).padStart(2, '0')+':'+String(this.getSeconds()).padStart(2, '0')
}
Date.prototype.dateTime=function() {
return this.getFullYear()+'-'+String(this.getMonth()+1).padStart(2, '0')+'-'+String(this.getDate()).padStart(2, '0')+' '+String(this.getHours()).padStart(2, '0')+':'+String(this.getMinutes()).padStart(2, '0')+':'+String(this.getSeconds()).padStart(2, '0')
}
Date.prototype.addTime=function(time) {
var time=time.split(":")
var rd=new Date(this.setHours(this.getHours()+parseInt(time[0])))
rd=new Date(rd.setMinutes(rd.getMinutes()+parseInt(time[1])))
return new Date(rd.setSeconds(rd.getSeconds()+parseInt(time[2])))
}
Date.prototype.addDate=function(time) {
var time=time.split("-")
var rd=new Date(this.setFullYear(this.getFullYear()+parseInt(time[0])))
rd=new Date(rd.setMonth(rd.getMonth()+parseInt(time[1])))
return new Date(rd.setDate(rd.getDate()+parseInt(time[2])))
}
Date.prototype.subDate=function(time) {
var time=time.split("-")
var rd=new Date(this.setFullYear(this.getFullYear()-parseInt(time[0])))
rd=new Date(rd.setMonth(rd.getMonth()-parseInt(time[1])))
return new Date(rd.setDate(rd.getDate()-parseInt(time[2])))
}
and then just:
new Date().date()
which returns current date in 'MySQL format'
for add time is
new Date().addTime('0:30:0')
which will add 30 minutes.... and so on
Solution built on the basis of other answers, while maintaining the timezone and leading zeros:
var d = new Date;
var date = [
d.getFullYear(),
('00' + d.getMonth() + 1).slice(-2),
('00' + d.getDate() + 1).slice(-2)
].join('-');
var time = [
('00' + d.getHours()).slice(-2),
('00' + d.getMinutes()).slice(-2),
('00' + d.getSeconds()).slice(-2)
].join(':');
var dateTime = date + ' ' + time;
console.log(dateTime) // 2021-01-41 13:06:01
Simple: just Replace the T.
Format that I have from my <input class="form-control" type="datetime-local" is :
"2021-02-10T18:18"
So just replace the T, and it would look like this: "2021-02-10 18:18" SQL will eat that.
Here is my function:
var CreatedTime = document.getElementById("example-datetime-local-input").value;
var newTime = CreatedTime.replace("T", " ");
Reference:
https://www.tutorialrepublic.com/faq/how-to-replace-character-inside-a-string-in-javascript.php#:~:text=Answer%3A%20Use%20the%20JavaScript%20replace,the%20global%20(%20g%20)%20modifier.
https://www.tutorialrepublic.com/codelab.php?topic=faq&file=javascript-replace-character-in-a-string

Categories

Resources