convert javascript date format to YYYY-MM-DDTHH:MM:SS - javascript

how to convert default date in javascript to YYYY-MM-DDTHH:MM:SS format.
new Date() returns Sun Aug 07 2016 16:38:34 GMT+0000 (UTC)
and i need the current date to above format.

As new Date().toISOString() will return current UTC time, to get local time in ISO String format we have to get time from new Date() function like the following method
document.write(new Date(new Date().toString().split('GMT')[0]+' UTC').toISOString().split('.')[0]);

You can use moment.js library to achieve this.
Try:
var moment = require('moment')
let dateNow = moment().format('YYYY-MM-DDTHH:MM:SS')

This could work :
var date = new Date();
console.log(date.getFullYear() + "-" + (date.getMonth()+1) + "-" + date.getDate() + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds());

For use the date in ISO 8601 format run the command lines below on NodeJS console or on browser console:
$ node
> var today = new Date(); // or
> var today = new Date(2016, 8, 7, 14, 06, 30); // or
> var today = new Date('2016-08-07T14:06:30');
> today; // Show the date in standard USA format. Grrrr!
> today.toISOString();
For more information, consult the documentation:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

moment is to large, you can use fecha
import fecha from 'fecha'
const uTime ="2019-10-21T18:57:33"
fecha.format(fecha.parse(uTime, "YYYY-MM-DD'T'HH:mm:ss"), 'YYYY.MM.DD HH:mm:ss')
// console.log(2019.10.21 18:57:33)

let date = new Date(Date.now());
date = now.toISOString().substr(0,now.toISOString().indexOf("."));
//2021-07-26T09:07:59

use this code:
new Date(new Date().toString().split('GMT')[0]+' UTC').toISOString().split('.')[0]);

Related

add 12 months for Now Date

Hi, I would like to add 12 months and subtract 1 day for my current
date.
Example :
valStartDate :2018-01-20
expected_date:2019-01-19
I try below code but error "getFullYear() not a function to allow"
this.endDate =this.valStartDate.getFullYear()+1+'-'+this.valStartDate.getMonth()+'-'+(this.valStartDate.getDate()-1);
Ensure that your given start date is a date and not a string.
var startDate = new Date(2018, 0, 20);
var startDatePlus12Months = new Date(startDate.setMonth(startDate.getMonth() + 12));
var expectedDate = new Date(startDatePlus12Months.getFullYear(), startDatePlus12Months.getMonth(), startDatePlus12Months.getDate() - 1);
Here is a method of abstracting the date you want, apply this the variable and you should be good to go.
var date = new Date(); // now
var newDate = new Date(date.getFullYear() + 1, date.getMonth(), date.getDate() - 1);
console.log(newDate.toLocaleDateString());
this.valStartDate.getFullYear() In order for this to work, this.valStartDate must be a valid javascript date and look the same format as new Date(); would give you.
Fri Apr 26 2019 11:52:15 GMT+0100 (British Summer Time)
this.endDate = new Date(this.endDate); // <= maybe you get a string date...
this.endDate.setMonth(this.endDate.getMonth() + 12);
this.endDate.setDate(this.endDate.getDate() - 1);
If you're getting your date from a server or from a previous Json format, maybe you need to convert it from string to Date first: this.endDate = new Date(this.endDate);. It seems this is your case.
This is easy with the help of Moment.js:
const startDate = moment('2018-01-20');
const endDate = startDate.add(12, 'months').subtract(1, 'days').toDate();

How to display just date and no time with UTC datestring in js?

Trying to display just the date by doing this:
let myDate="2015-03-08T04:49:49.431Z";
console.log(new Date(myDate).toUTCString('dd-mm-yyyy'));
Still returns the time , how can I just return the date?
var myDate="2015-03-08T04:49:49.431Z";
new Date(myDate).toLocaleDateString(); // "3/8/2015"
new Date(myDate).toDateString(); // "Sun Mar 08 2015"
You can check all other methods here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
You could do something like:
let myDate = "2015-03-08T04:49:49.431Z";
let date = new Date(myDate);
let dateString = ("0" + date.getUTCDate()).slice(-2) + "-" + ("0" + (date.getUTCMonth()+1)).slice(-2) + "-" + date.getUTCFullYear();
console.log(dateString);
.toUTCString() does not accept any arguments.

Date comparison getting error

we stuck date comparison, we tried the below code. EndDate value is related to jan 21, 2016 but in alert showing showing Fri Sep 01 2017 10:10:10 GMT+0530 (India Standard Time), could you please share me your ideas
var endDateVal = "21/01/2016 10:10:10".replace(/-/gi, "/");
alert(new Date(endDateVal));
if (new Date(endDateVal) > new Date()) {
alert("Last end date should be minor than today");
}
Fiddle
The date is formatted incorrectly. The date needs to be an ISO 8601 or IETF-compliant RFC 2822 formatted date, like:
2016-01-21T10:10:10+05:30
To format the date you have you could do some thing like:
var dateVars = "21/01/2016 10:10:10".match(/\d+/g);
var reformattedDate = dateVars[2] + '-' + dateVars[1] + '-' + dateVars[0] + 'T' + dateVars[3] + ':' + dateVars[4] + ':' + dateVars[5] + '+05:30';
new Date(reformattedDate);
First, new Date("21/01/2016 10:10:10") returns Invalid Date. Default format for Date is mm/dd/yyyy and not dd/mm/yyyy.
Second, when comparing dates, you should use date.getTime() instead.
Following is a sample code.
var endDateVal = "02/21/2016 10:10:10";
var d1 = new Date(endDateVal)
var d2 = new Date();
console.log(d1, d2)
if (+d1 > +d2) {
alert("Last end date should be minor than today");
}
You need to swap your day/month around to 01/21/2016 10:10:10.
Also, Im not sure why you are using .replace(/-/gi, "/"); as this is replacing a - with / where your date does not have any -.

Display the tomorrow's date

I'm trying to create a JS code which displays tthe tomorrow's date.
This is the code I tried :
var d = new Date.today().addDays(1).toString("dd-mm-yyyy");
but it won't work for me.
How can I solve it ?
var todayDate = new Date();
todayDate .setDate(todayDate .getDate() + 1);
Then todayDate contains tomorrow date
Try this :
var d = new Date();
var tomorrowDate = d.getDate() + 1;
d.setDate(tomorrowDate);
document.write("Tommorow date : " + d );
Output :
Tommorow date : Fri Jul 05 2013 19:16:50 GMT+0530 (IST)
var d = new Date();
d.setDate(d.getDate() + 1)
console.log(d)
If you're going to deal a lot with dates, I'd recommend you to use Moment.js. It allows you to do exactly what you want, aswell much more things:
var date = moment().add("days", 1);
// If displaying this date, use the following to format it in your culture.
// Will be mm-dd-yyyy in en-US, I believe
date.format("L");
Docs: http://momentjs.com/docs/

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