JavaScriptカウントダウンMySQL DateTime形式へ
-
05-10-2019 - |
質問
MySQLデータベースから来る日付があります datetime
形式、ようなもの 2010-09-24 11:30:12
. 。そして、私は時間のカウントダウンを示す方法が必要です:その日までの分。
私はJavaScriptの日付にあまり慣れていないので、どんな助けも激化します。ありがとう。
解決
あなたはを使用することをお勧めします UNIX_TIMESTAMP()
MySQLで機能して日付を返します UNIXタイム形式 (1970年1月1日以来の秒数)。ターゲットの日付がそうであるとしましょう '2011-01-01 00:00:00'
(実際には、おそらく定数ではなく、テーブルからフィールドを持っているでしょう):
SELECT UNIX_TIMESTAMP('2011-01-01 00:00:00') AS timestamp;
+---------------+
| timestamp |
+---------------+
| 1293836400 |
+---------------+
1 row in set (0.00 sec)
その後、を使用できます getTime()
の方法 Date
JavaScriptのオブジェクト現在の時間と目標時間の間の秒数を計算するためのオブジェクト。秒数がかかると、時間、分、日を簡単に計算できます。
var target = 1293836400; // We got this from MySQL
var now = new Date(); // The current tume
var seconds_remaining = target - (now.getTime() / 1000).toFixed(0);
var minutes_remaining = seconds_remaining / 60;
var hours_remaining = minutes_remaining / 60;
var days_remaining = hours_remaining / 24;
alert(seconds_remaining + ' seconds'); // 8422281 seconds
alert(minutes_remaining + ' minutes'); // 140371.35 minutes
alert(hours_remaining + ' hours'); // 2339.5225 hours
alert(days_remaining + ' days'); // 97.48010416666666 days
他のヒント
jQueryプラグインを使用できます http://keith-wood.name/countdown.html
mysqlの日付と時刻をJS変数としてJSに渡すだけです
構文はです
$(selector).countdown({until: liftoffTime, format: 'HMS'})
JSコードはこちら
function mysqlTimeStampToDate(timestamp) {
//function parses mysql datetime string and returns javascript Date object
//input has to be in this format: 2010-09-24 11:30:12
var regex=/^([0-9]{2,4})-([0-1][0-9])-([0-3][0-9]) (?:([0-2][0-9]):([0-5][0-9]):([0-5][0-9]))?$/;
var parts=timestamp.replace(regex,"$1 $2 $3 $4 $5 $6").split(' ');
return new Date(parts[0],parts[1]-1,parts[2],parts[3],parts[4],parts[5]);
}
$('#selector').countdown({until: mysqlTimeStampToDate(<? echo "2010-09-24 11:30:12" ?>), format: 'HMS'});
があります date.parse() 機能する可能性のある方法。
所属していません StackOverflow