如何在mysql中使用纽约时区获取最后12个月的数据?

时间:2018-11-15 10:44:57

标签: php mysql mysqli

我有一个表transaction,该表的UTC日期为created,我想用mysql的New York Timezone获取所有数据,有人可以帮我吗? 这是我的查询

$user_db = Common_Users_Helper::get_user_db_conn($this->session->userdata('id'), '');
$user_db->select('amount, created,MONTHNAME(created) as month, sponsorion_fees, processor_fees, amount_after_fees, SUM(amount_after_fees) as total');
$user_db->from('transaction');
$user_db->order_by('id', 'ASC');
$user_db->group_by('month');
$user_db->where('record_owner_user_id', $id);
$user_db->where('is_one_time_purchase', 'Y');
$user_db->where('created <= utc_timestamp() and created >= Date_add(utc_timestamp(),interval - 12 month)');
$query = $user_db->get();
//echo $user_db->last_query(); die;
$result = $query->result_array();

1 个答案:

答案 0 :(得分:1)

您可以通过将PHP中的时区设置为纽约来获取纽约的当前时间,

 date_default_timezone_set('America/New_York');
 $currentdatetime = date('Y-m-d H:i:s');

然后在您的查询中,将utc_timestamp()替换为$currentdatetime

$user_db->where('created <= "'.$currentdatetime.'" and created >= Date_add("'.$currentdatetime.'",interval - 12 month)');

要显示纽约时区的创建时间,

// Set based timezone as UTC
date_default_timezone_set('UTC');
$date = '2018-11-15 10:56:00';
$timestamp = strtotime($date); // create timestamp

date_default_timezone_set('America/New_York'); // Set required timezone
echo $nydate = date('Y-m-d H:i:s', $timestamp); // Convert timestamp in NY