在mySQL中存储javascript Date() [英] Storing javascript Date() in mySQL

查看:72
本文介绍了在mySQL中存储javascript Date()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有一个javascript变量,它记录当前的日期和时间,如下所示:

  var time_of_call; 
time_of_call = new Date();

我需要将它存储在MySQL数据库中。当我尝试上传它时,该列只显示为空白但我不确定我做错了什么。我知道这不是mysql查询的问题,因为我尝试输入不同的值并且工作正常。



我将列设置为 DATETIME 我正在上传未格式化的值。有人可以用不同的方式解释我需要做些什么吗?



感谢您的帮助



P.s。我不能使用 NOW()因为我正在使用它来捕获实际捕获记录的时间,而此time_of_call记录了呼叫实际进入的时间。

解决方案

在JavaScript中,Date对象的基础值以毫秒为单位,而Unix服务器(以及内部的MySQL)使用整秒。



获取javascript日期对象的基础值:

  var pDate = new Date(); 
var pDateSeconds = pDate.valueOf()/ 1000;

从此处,您将把它发送到服务器...由您决定是否或不要将它除以1000,但必须在某处完成。从这个值,你可以调用像PHP的日期('Y-m-d H:i:s',$ pDateSeconds);它可以在MySQL中使用内置函数:



$ sql ='UPDATE table_name
SET field_name = FROM_UNIXTIME('。$ pDateSeconds。')
WHERE field_name ='。$ row_id;


I currently have a javascript variable which records the current date and time like so:

var time_of_call;
time_of_call = new Date();

and I need to store it in a MySQL database. When I try to upload it, the column just appears blank but I'm not sure what I'm doing wrong. I know it's not a problem with the mysql query because I have tried entering different values and it works OK.

I have the column set to DATETIME and I am uploading the value unformatted. Could someone please explain what I need to do differently?

Thanks for any help

P.s. I can't use NOW() because I am using that to capture the time that the record is actually captured, and this time_of_call records the time a call actually comes in.

解决方案

In JavaScript, the underlying value of a Date object is in milliseconds, while Unix servers (and MySQL internally) uses whole seconds.

To get the underlying value for a javascript date object:

var pDate = new Date();
var pDateSeconds = pDate.valueOf()/1000;

From here, you'll send it to the server... it is up to you whether or not to divide it by 1000, but it has to be done somewhere. From this value, you could just call something like PHP's date('Y-m-d H:i:s', $pDateSeconds); on it.

Or, you could just use the built-in function in MySQL:

$sql = 'UPDATE table_name 
        SET field_name=FROM_UNIXTIME('.$pDateSeconds.') 
        WHERE field_name='.$row_id;

这篇关于在mySQL中存储javascript Date()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆