JS 날짜 시간을 MySQL 날짜 시간으로 변환
누구든지 JS dateTime을 MySQL datetime으로 변환하는 방법을 알고 있습니까? 또한 JS 날짜 시간에 특정 분을 추가 한 다음 MySQL 날짜 시간으로 전달하는 방법이 있습니까?
JS는이를 수행하기에 충분한 기본 도구를 보유하고 있지만 꽤 성가시다.
/**
* 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());
};
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);
또는 더 짧게 :
new Date().toISOString().slice(0, 19).replace('T', ' ');
산출:
2012-06-22 05:40:06
시간대 제어를 포함한 고급 사용 사례의 경우 http://momentjs.com/ 사용을 고려 하십시오 .
require('moment')().format('YYYY-MM-DD HH:mm:ss');
momentjs에 대한 간단한 대안 은 https://github.com/taylorhakes/fecha를 고려 하십시오.
require('fecha').format('YYYY-MM-DD HH:mm:ss')
나는 method를 사용하여 솔루션이 덜 복잡 할 수 있다고 생각 toISOString()
하며 광범위한 브라우저 호환성을 가지고 있습니다.
따라서 당신의 표현은 하나의 라이너가 될 것입니다.
new Date().toISOString().slice(0, 19).replace('T', ' ');
생성 된 출력 :
"2017-06-29 17:54:04"
임의의 날짜 문자열의 경우
// 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 );
또는 단일 회선 솔루션
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
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.
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.
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/
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
@Paulo Roberto의 답변 은 새 날 을 시작할 때 잘못된 결과를 생성합니다 (댓글을 남길 수 없음). 예를 들면 다음과 같습니다.
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 대신 6 월 22 일을 받았습니다!
var _t = new Date();
UTC 형식을 원한다면
_t.toLocaleString('indian', { timeZone: 'UTC' }).replace(/(\w+)\/(\w+)\/(\w+), (\w+)/, '$3-$2-$1 $4');
또는
_t.toISOString().slice(0, 19).replace('T', ' ');
특정 시간대에 원하는 경우
_t.toLocaleString('indian', { timeZone: 'asia/kolkata' }).replace(/(\w+)\/(\w+)\/(\w+), (\w+)/, '$3-$2-$1 $4');
참고 URL : https://stackoverflow.com/questions/5129624/convert-js-date-time-to-mysql-datetime
'Programing' 카테고리의 다른 글
MySQL 5.7 완전히 제거하기 (0) | 2020.07.20 |
---|---|
정규 표현식을 사용하여 Ruby의 문자열에서 부분 문자열 추출 (0) | 2020.07.20 |
FragmentPagerAdapter getItem이 호출되지 않았습니다 (0) | 2020.07.20 |
에뮬레이터에서 AVD를 시작할 수 없음 : QT 라이브러리를 찾을 수 없음 (0) | 2020.07.20 |
ID로 사용자 프로필 사진 가져 오기 (0) | 2020.07.20 |