Risposte:
Mentre JS possiede abbastanza strumenti di base per farlo, è piuttosto goffo.
/**
* 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());
};
Dateoggetto. new Date().toMysqlFormat()o new Date(2014,12,14).toMysqlFormat()altro.
toISOString come target un browser moderno, consiglio l' approccio di Gajus .
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);
o anche più breve:
new Date().toISOString().slice(0, 19).replace('T', ' ');
Produzione:
2012-06-22 05:40:06
Per casi d'uso più avanzati, incluso il controllo del fuso orario, considera l'utilizzo di http://momentjs.com/ :
require('moment')().format('YYYY-MM-DD HH:mm:ss');
Per un'alternativa leggera a momentjs, considera https://github.com/taylorhakes/fecha
require('fecha').format('YYYY-MM-DD HH:mm:ss')
var d = new Date(); d.toISOString().split('T')[0]+' '+d.toTimeString().split(' ')[0];
Penso che la soluzione possa essere meno goffa usando il metodo toISOString(), ha un'ampia compatibilità con il browser.
Quindi la tua espressione sarà una battuta:
new Date().toISOString().slice(0, 19).replace('T', ' ');
L'output generato:
"29/06/2017 17:54:04"
new Date(1091040026000).toISOString().slice(0, 19).replace('T', ' ');
Date del fuso orario di js . Mentre il tuo restituisce l'ora UTC sottostante nel formato DATETIME di MySQL. Nella maggior parte dei casi la memorizzazione dell'UTC può essere migliore e in entrambi i casi la tabella dei dati dovrebbe probabilmente fornire informazioni sulla posizione in un campo. In alternativa, convertire in ora locale è piuttosto semplice: usare ... - Date.getTimezoneOffset() * 60 * 1000(NB regola anche l'ora legale dove applicabile).
Valore temporale JS per MySQL
var datetime = new Date().toLocaleString();
O
const DATE_FORMATER = require( 'dateformat' );
var datetime = DATE_FORMATER( new Date(), "yyyy-mm-dd HH:MM:ss" );
O
const MOMENT= require( 'moment' );
let datetime = MOMENT().format( 'YYYY-MM-DD HH:mm:ss.000' );
puoi inviarlo in parametri, funzionerà.
Per una stringa data arbitraria,
// 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 );
O una soluzione a linea singola,
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 );
Questa soluzione funziona anche per Node.js quando si utilizza Timestamp in mysql.
La prima risposta di @Gajus Kuizinas sembra modificare il prototipo toISOString di mozilla
Soluzione completa (per mantenere il fuso orario) utilizzando il concetto di risposta @Gajus:
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
new Date (). toISOString (). slice (0, 10) + "" + new Date (). toLocaleTimeString ('en-GB');
Funzionante al 100%
Ho fornito semplici esempi di formato data JavaScript, per favore controlla il codice sottostante
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
Utilizzando momentjs
var date = moment().format('YYYY-MM-DD H:mm:ss');
console.log(date) // 2016-06-23 15:59:08
Esempio per favore controlla https://jsfiddle.net/sjy3vjwm/2/
Il modo più semplice e corretto per convertire JS Date in formato datetime SQL che mi viene in mente è questo. Gestisce correttamente la differenza di fuso orario.
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
Attenzione che la risposta di @Paulo Roberto produrrà risultati errati al turno del nuovo giorno (non posso lasciare commenti). Ad esempio :
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
Abbiamo il 22 giugno invece del 23!
var _t = new Date();
se vuoi semplicemente il formato UTC
_t.toLocaleString('indian', { timeZone: 'UTC' }).replace(/(\w+)\/(\w+)\/(\w+), (\w+)/, '$3-$2-$1 $4');
o
_t.toISOString().slice(0, 19).replace('T', ' ');
e se vuoi in un fuso orario specifico, allora
_t.toLocaleString('indian', { timeZone: 'asia/kolkata' }).replace(/(\w+)\/(\w+)\/(\w+), (\w+)/, '$3-$2-$1 $4');
Sto usando questo tempo molto lungo ed è molto utile per me, usalo come preferisci
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])))
}
e poi solo:
new Date().date()
che restituisce la data corrente in 'formato MySQL'
per aggiungere tempo è
new Date().addTime('0:30:0')
che aggiungerà 30 minuti .... e così via