簡體   English   中英

將 JS 日期時間轉換為 MySQL 日期時間

[英]Convert JS date time to MySQL datetime

有誰知道如何將 JS 日期時間轉換為 MySQL 日期時間? 還有一種方法可以將特定的分鍾數添加到 JS 日期時間,然后將其傳遞給 MySQL 日期時間?

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');

對於的輕量級替代,請考慮https://github.com/taylorhakes/fecha

require('fecha').format('YYYY-MM-DD HH:mm:ss')

我認為使用toISOString()方法可以使解決方案不那么笨拙,它具有廣泛的瀏覽器兼容性。

所以你的表達式將是一個單行:

new Date().toISOString().slice(0, 19).replace('T', ' ');

生成的輸出:

“2017-06-29 17:54:04”

雖然 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());
};

MySQL 的 JS 時間值

var datetime = new Date().toLocaleString();

或者

const DATE_FORMATER = require( 'dateformat' );
var datetime = DATE_FORMATER( new Date(), "yyyy-mm-dd HH:MM:ss" );

或者

const MOMENT= require( 'moment' );
let datetime = MOMENT().format( 'YYYY-MM-DD  HH:mm:ss.000' );

你可以在 params 中發送它,它會起作用。

對於任意日期字符串,

// 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 );

在 mysql 中使用時間戳時,此解決方案也適用於 Node.js。

@Gajus Kuizinas 的第一個答案似乎修改了 mozilla 的 toISOString 原型

new Date().toISOString().slice(0, 10)+" "+new Date().toLocaleTimeString('en-GB');

古老的DateJS庫有一個格式化例程(它覆蓋了“.toString()”)。 你也可以很容易地自己做一個,因為“日期”方法為你提供了你需要的所有數字。

我遇到的將 JS 日期轉換為 SQL 日期時間格式的最簡單的正確方法是這個。 它正確處理時區偏移。

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 

我們有 6 月 22 日而不是 23 日!

使用@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

簡短版本:

 // 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 時間通常是在 MySQL 中存儲時間戳的最佳選擇 如果您沒有 root 訪問權限,請在連接開始時運行set time_zone = '+00:00'

使用方法 convert_tz 在 MySQL 中顯示特定時區的時間戳

select convert_tz(now(), 'SYSTEM', 'America/Los_Angeles');

JavaScript 時間戳基於您設備的時鍾並包括時區。 在發送任何由 JavaScript 生成的時間戳之前,您應該將它們轉換為 UTC 時間。 JavaScript 有一個名為 toISOString() 的方法,該方法將 JavaScript 時間戳格式化為看起來類似於 MySQL 時間戳,並將時間戳轉換為 UTC 時間。 最后的清理發生在切片和替換。

let timestmap = new Date()
timestmap.toISOString().slice(0, 19).replace('T', ' ')

長版本顯示正在發生的事情:

 // 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)

不同時區的日期時間

這使用@Gayus 解決方案,使用從toISOString()輸出的格式,但它會調整分鍾以考慮時區。 最終格式: 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', ' '));

我給出了簡單的 JavaScript 日期格式示例,請查看以下代碼

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

var date = moment().format('YYYY-MM-DD H:mm:ss');

console.log(date) // 2016-06-23 15:59:08

示例請查看https://jsfiddle.net/sjy3vjwm/2/

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');

一個簡單的解決方案是向 MySQL 發送時間戳並讓它進行轉換。 Javascript 使用以毫秒為單位的時間戳,而 MySQL 期望它們以秒為單位 - 因此需要除以 1000:

// 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';

使用toJSON()日期函數如下:

 var sqlDatetime = new Date(new Date().getTime() - new Date().getTimezoneOffset() * 60 * 1000).toJSON().slice(0, 19).replace('T', ' '); console.log(sqlDatetime);

簡單:只需替換我的 <input class="form-control" type="datetime-local" 中的 T. 格式為:“2021-02-10T18:18”

所以只需替換 T,它看起來像這樣:“2021-02-10 18:18”SQL 會吃掉它。

這是我的功能:

var CreatedTime = document.getElementById("example-datetime-local-input").value;

var newTime = CreatedTime.replace("T", " ");

參考: https : //www.tutorialrepublic.com/faq/how-to-replace-character-inside-a-string-in-javascript.php# :~: text=Answer%3A%20Use%20the%20JavaScript%20replace ,%20global%20(%20g%20)%20 修飾符

https://www.tutorialrepublic.com/codelab.php?topic=faq&file=javascript-replace-character-in-a-string

如果您使用的是Date-fns ,則可以使用格式function 輕松實現該功能。

const format = require("date-fns/format");
const date = new Date();

const formattedDate = format(date, "yyyy-MM-dd HH:mm:ss")

我用了這么久,對我很有幫助,隨便用

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])))
}

然后只是:

new Date().date()

以“MySQL 格式”返回當前日期

添加時間是

new Date().addTime('0:30:0')

這將增加 30 分鍾......等等

解決方案建立在其他答案的基礎上,同時保持時區和前導零:

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

這是迄今為止我能想到的最簡單的方法

new Date().toISOString().slice(0, 19).replace("T", " ")

我需要一個 function 以在 javascript 中返回 sql 時間戳格式,形成一個選擇性的時區

 <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>

這是最簡單的方法 -

new Date().toISOString().slice(0, 19).replace("T", " ")

我很驚訝沒有人提到 javascript 的瑞典日期時間格式。
瑞典語的 BCP 47 語言標簽是 sv-SE,您可以將其用於new Date “區域設置”參數。
我並不是說這是一個好習慣,但它確實有效。

 console.log(new Date().toLocaleString([['sv-SE']])) //2022-09-10 17:02:39

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM