Odpowiedzi:
Chociaż JS ma wystarczającą ilość podstawowych narzędzi, aby to zrobić, jest to dość niezgrabne.
/**
* 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());
};
Dateprzedmiotu. new Date().toMysqlFormat()lub new Date(2014,12,14).toMysqlFormat()cokolwiek.
toISOString .
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);
lub jeszcze krócej:
new Date().toISOString().slice(0, 19).replace('T', ' ');
Wynik:
2012-06-22 05:40:06
W przypadku bardziej zaawansowanych przypadków użycia, w tym kontrolowania strefy czasowej, rozważ użycie http://momentjs.com/ :
require('moment')().format('YYYY-MM-DD HH:mm:ss');
Lekka alternatywa dla momentjsrozważ 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];
Myślę, że rozwiązanie może być mniej niezgrabne przy użyciu metody toISOString(), ma szeroką kompatybilność z przeglądarkami.
Twoje wyrażenie będzie więc jednowierszowe:
new Date().toISOString().slice(0, 19).replace('T', ' ');
Wygenerowane dane wyjściowe:
„2017-06-29 17:54:04”
new Date(1091040026000).toISOString().slice(0, 19).replace('T', ' ');
Date„s przesunięcie strefy czasowej . Podczas gdy twój zwraca podstawowy czas UTC w formacie MySQL DATETIME. W większości przypadków przechowywanie czasu UTC może być lepsze, aw każdym przypadku tabela danych powinna prawdopodobnie zawierać informacje o lokalizacji w jednym polu. Alternatywnie, konwersja na czas lokalny jest dość łatwa: użyj ... - Date.getTimezoneOffset() * 60 * 1000(uwaga: dostosowuje się również do czasu letniego, jeśli dotyczy).
Wartość czasu JS dla MySQL
var datetime = new Date().toLocaleString();
LUB
const DATE_FORMATER = require( 'dateformat' );
var datetime = DATE_FORMATER( new Date(), "yyyy-mm-dd HH:MM:ss" );
LUB
const MOMENT= require( 'moment' );
let datetime = MOMENT().format( 'YYYY-MM-DD HH:mm:ss.000' );
możesz wysłać to w params, to zadziała.
W przypadku dowolnego ciągu daty
// 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 );
Lub rozwiązanie z jedną linią,
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 );
To rozwiązanie działa również dla Node.js podczas używania Timestamp w mysql.
Pierwsza odpowiedź @Gajusa Kuizinasa wydaje się modyfikować prototyp Mozilli toISOString
Pełne obejście (w celu utrzymania strefy czasowej) przy użyciu koncepcji odpowiedzi @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
nowa data (). toISOString (). slice (0, 10) + "" + nowa data (). toLocaleTimeString ('en-GB');
100% sprawne
Podałem proste przykłady formatu daty JavaScript, sprawdź poniższy kod
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
Korzystanie z momentjs
var date = moment().format('YYYY-MM-DD H:mm:ss');
console.log(date) // 2016-06-23 15:59:08
Przykład sprawdź https://jsfiddle.net/sjy3vjwm/2/
Najłatwiejszym poprawnym sposobem przekonwertowania JS Date na format daty i godziny SQL, który mi się przytrafił, jest ten. Prawidłowo obsługuje przesunięcie strefy czasowej.
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
Pamiętaj, że odpowiedź @Paulo Roberto da nieprawidłowe wyniki po włączeniu nowego dnia (nie mogę zostawiać komentarzy). Na przykład :
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
Mamy 22 czerwca zamiast 23!
var _t = new Date();
jeśli chcesz po prostu format UTC
_t.toLocaleString('indian', { timeZone: 'UTC' }).replace(/(\w+)\/(\w+)\/(\w+), (\w+)/, '$3-$2-$1 $4');
lub
_t.toISOString().slice(0, 19).replace('T', ' ');
i jeśli chcesz w określonej strefie czasowej
_t.toLocaleString('indian', { timeZone: 'asia/kolkata' }).replace(/(\w+)\/(\w+)\/(\w+), (\w+)/, '$3-$2-$1 $4');
Używam tego długo i jest to dla mnie bardzo pomocne, używaj, jak chcesz
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])))
}
a potem tylko:
new Date().date()
która zwraca aktualną datę w 'formacie MySQL'
za dodatkowy czas
new Date().addTime('0:30:0')
co wydłuży 30 minut ... i tak dalej