You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取正确的PHP Timestamp值?代码无法返回目标格式求助

Fixing Your Millisecond Timestamp Issue in PHP

Hey there! Let's break down what's wrong with your current code and get you that 13-digit millisecond timestamp (like 1516426272898) you're after.

What's Wrong With Your Current Code?

The key issue is how you're using date_timestamp_get():

  • This function expects a DateTime object as its parameter, but you're passing a formatted date string (the output of date("l, F \ j,Y, h:i:s A")). Since it can't parse the string into a valid timestamp source, it fails to return the value you want.

Solution 1: Use DateTime Class for Millisecond Timestamps

If you want to work with DateTime (which is great for timezone handling and date manipulation), here's how to get the 13-digit timestamp:

date_default_timezone_set('Asia/Kolkata');
$dateTime = new DateTime();

// Calculate millisecond timestamp: seconds * 1000 + milliseconds from microseconds
$millisecondTimestamp = $dateTime->getTimestamp() * 1000 + floor($dateTime->format('u') / 1000);

echo $millisecondTimestamp;
  • getTimestamp() gives you the standard 10-digit second-based timestamp.
  • format('u') returns 6-digit microseconds; dividing by 1000 converts it to 3-digit milliseconds, which we add to the scaled-up second timestamp.

Solution 2: A Simpler Direct Approach

If you don't need the full DateTime functionality, you can use microtime(true) to get a float-based timestamp (including microseconds) and convert it directly:

date_default_timezone_set('Asia/Kolkata');
$microtime = microtime(true);

// Multiply by 1000 and cast to integer to get 13-digit milliseconds
$millisecondTimestamp = (int)($microtime * 1000);

echo $millisecondTimestamp;

This works because microtime(true) returns the current time as a float (e.g., 1705321234.5678), where the decimal part represents microseconds. Multiplying by 1000 shifts the decimal to get milliseconds, and casting to int trims off any extra precision.

Bonus: If You Need a Timestamp From a Specific Formatted Date

If your end goal is to generate a millisecond timestamp from a pre-existing formatted date string (not the current time), you can parse the string into a DateTime object first:

date_default_timezone_set('Asia/Kolkata');
$dateStr = "Monday, January 15, 2024, 03:45:10 PM";

// Parse the string into a DateTime object using the same format you used to generate it
$dateTime = DateTime::createFromFormat("l, F j,Y, h:i:s A", $dateStr);

// Convert to millisecond timestamp (note: no millisecond data in the original string, so we append 0s)
$millisecondTimestamp = $dateTime->getTimestamp() * 1000;

echo $millisecondTimestamp;

内容的提问来源于stack exchange,提问作者Game Mod Apk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:44:28