Yanıtlar:
JS bunu yapmak için yeterli temel araca sahip olsa da, oldukça kullanışsız.
/**
* 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());
};
Datenesne kullanıyorsun. new Date().toMysqlFormat()ya new Date(2014,12,14).toMysqlFormat()da her neyse.
toISOStringyaklaşımını öneririm .
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);
hatta daha kısa:
new Date().toISOString().slice(0, 19).replace('T', ' ');
Çıktı:
2012-06-22 05:40:06
Saat dilimini kontrol etme dahil daha gelişmiş kullanım örnekleri için http://momentjs.com/ kullanmayı düşünün :
require('moment')().format('YYYY-MM-DD HH:mm:ss');
Hafif bir alternatif için momentjshttps://github.com/taylorhakes/fecha düşünün
require('fecha').format('YYYY-MM-DD HH:mm:ss')
var d = new Date(); d.toISOString().split('T')[0]+' '+d.toTimeString().split(' ')[0];
Yöntem kullanarak çözümün daha az hantal olabileceğini düşünüyorum, toISOString()geniş bir tarayıcı uyumluluğuna sahip.
Yani ifadeniz tek satırlık olacak:
new Date().toISOString().slice(0, 19).replace('T', ' ');
Üretilen çıktı:
"2017-06-29 17:54:04"
new Date(1091040026000).toISOString().slice(0, 19).replace('T', ' ');
Date'nın saat diliminde offset . Oysa sizinki, temel UTC saatini MySQL DATETIME biçiminde döndürür. Çoğu durumda UTC'yi saklamak daha iyi olabilir ve her iki durumda da veri tablonuz muhtemelen bir alanda konum bilgisi vermelidir. Alternatif olarak, yerel saate dönüştürmek oldukça kolaydır: kullanın ... - Date.getTimezoneOffset() * 60 * 1000(NB, uygulanabildiği yerde Yaz Saati Uygulamasını da ayarlar).
MySQL için JS zaman değeri
var datetime = new Date().toLocaleString();
VEYA
const DATE_FORMATER = require( 'dateformat' );
var datetime = DATE_FORMATER( new Date(), "yyyy-mm-dd HH:MM:ss" );
VEYA
const MOMENT= require( 'moment' );
let datetime = MOMENT().format( 'YYYY-MM-DD HH:mm:ss.000' );
bunu params olarak gönderebilirsiniz, çalışacaktır.
Rasgele tarih dizesi için,
// 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 );
Veya tek hatlı çözüm,
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 );
Bu çözüm, mysql'de Timestamp kullanırken Node.js için de işe yarar.
@Gajus Kuizinas'ın ilk cevabı mozilla'nın toISOString prototipini değiştiriyor gibi görünüyor
@Gajus yanıt konseptini kullanarak (saat dilimini korumak için) tam çözüm:
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 (). dilim (0, 10) + "" + new Date (). toLocaleTimeString ('en-GB');
% 100 çalışıyor
Basit JavaScript tarih biçimi örnekleri verdim, lütfen aşağıdaki kodu kontrol edin
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
Momentjs kullanma
var date = moment().format('YYYY-MM-DD H:mm:ss');
console.log(date) // 2016-06-23 15:59:08
Örnek lütfen https://jsfiddle.net/sjy3vjwm/2/ adresini kontrol edin
JS Tarihini SQL datetime biçimine dönüştürmenin en kolay doğru yolu budur. Saat dilimi farkını doğru şekilde işler.
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
@Paulo Roberto yanıtının yeni günde dönüşte yanlış sonuçlar üreteceğine dikkat edin (yorum bırakamam). Örneğin :
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
23 yerine 22 Haziran'ımız var!
var _t = new Date();
sadece UTC formatını istiyorsanız
_t.toLocaleString('indian', { timeZone: 'UTC' }).replace(/(\w+)\/(\w+)\/(\w+), (\w+)/, '$3-$2-$1 $4');
veya
_t.toISOString().slice(0, 19).replace('T', ' ');
ve belirli bir saat diliminde isterseniz
_t.toLocaleString('indian', { timeZone: 'asia/kolkata' }).replace(/(\w+)\/(\w+)\/(\w+), (\w+)/, '$3-$2-$1 $4');
Bu kadar uzun süredir kullanıyorum ve benim için çok faydalı, istediğin gibi kullan
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])))
}
ve sonra sadece:
new Date().date()
geçerli tarihi 'MySQL formatında' döndürür
ek zaman için
new Date().addTime('0:30:0')
30 dakika ekleyecek .... vb.