【问题标题】:Transform time in JSON into actual time played PHP [closed]将 JSON 中的时间转换为实际播放 PHP 的时间 [关闭]
【发布时间】:2016-04-30 17:12:35
【问题描述】:

我正在开发一个应用程序,我请求了整个游戏的游戏时间,从他们购买到现在的特定用户,这是我在 JSON 中得到的结果。

{ 
  "TotalTimePlayed": "PT48M26.4570633S"
}

我需要将其转换为:月、日、小时、分钟、秒

在我看来,这就是我的变量的显示方式:

{{ $TotalTimePlayed }}

我如何将其转换为可读时间?

/********** 编辑 ****************/

我从帮助文件中插入了 prettyDate 函数,但显示的时间错误

{{ prettyDate($TotalTimePlayed) }}

在 helper.php 文件中:

function prettyDate($date) {
    return date("d h, I", strtotime($date));
}

/***** 编辑 ******/

我希望它喜欢这样的示例: 1M、22D、6H、45M、56S

【问题讨论】:

  • 您希望人们玩 .. 个月的单个游戏会话?
  • 至少尝试一下。随便...
  • 谷歌“JavaScript 时间对象”
  • 您能创建一个我们可以使用的Minimal, Complete, and Verifiable Example 吗?这将使您更有可能获得问题的高质量答案。
  • 先告诉我们它对应的月数、天数等​​是48分钟还是月? 4570633 是秒数吗,它与 48 和 26 有什么关系?

标签: javascript php time


【解决方案1】:

持续时间格式为ISO 8601 format

你可以这样继续:

1。使用日期间隔

给定的格式几乎是 PHP 的 DateInterval class 所期望的格式,除了它不允许小数。

所以,我们可以先去掉那个小数部分,然后利用这个类来生成输出:

$json = '{ 
  "TotalTimePlayed": "PT48M26.4570633S"
}';

// Interpret JSON 
$obj = json_decode($json);

// Get value, and strip fractional part (not supported by DateInterval)
$value = preg_replace("/\.\d+/", "", $obj->TotalTimePlayed);

// Turn this into a DateInterval instance
$interval = new DateInterval($value);

// Use format method to get the desired output
echo $interval->format('%m months, %d days, %h hours, %i minutes, %s seconds');

示例数据的输出为:

0 个月 0 天 0 小时 48 分钟 26 秒

2。使用 preg_match_all 提取数字

这个替代方案不使用DateInterval,因此可以处理小数秒:

// Sample data:
$json = '{ 
  "TotalTimePlayed": "PT48M26.4570633S"
}';

// Interpret JSON 
$obj = json_decode($json);

// Extract all numbers in that "PT" format into an array
preg_match_all("/[\d.]+/", $obj->TotalTimePlayed, $parts);

// Convert string representations to numbers
$parts = array_map('floatval', $parts[0]);

// Pad the array on the left in order to get 5 elements (months, days, hours, minutes, seconds)
$parts = array_pad($parts, -5, 0);

// Output (just for checking)
echo json_encode($parts);

输出:

[0,0,0,48,26.4570633]

如果您不想要秒的小数部分,则将上述代码中的'floatval' 替换为'intval'

$parts = array_map('intval', $parts[0]);

然后示例将作为输出:

[0,0,0,48,26]

然后你可以这样做:

$playtime = $parts[0] . " months, " .
            $parts[1] . " days, " .
            $parts[2] . " hours, " .
            $parts[3] . " minutes, and " .
            $parts[4] . " seconds";

【讨论】:

  • 好的,感谢您的意见,我会看看我能做什么
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-04-19
  • 1970-01-01
  • 1970-01-01
  • 2016-12-31
  • 2011-07-29
  • 1970-01-01
  • 2014-08-30
相关资源
最近更新 更多