Random date in a view with Twig

2019-08-15 07:57发布

Out of curiosity, How can I generate a random date with Twig ?
(Its for improve the realisme of a test page, news,blog etc)

I know how to render the actual date,but I think it can be better with a random one

标签: date random twig
3条回答
Melony?
2楼-- · 2019-08-15 08:31

Random date

{{ random(+'now'|date('U'))|date('Y-m-d') }}

Random date greater then some date

{% set startDate = '2010-01-01'|date('U') %}
{{ (random(+'now'|date('U') - startDate) + startDate )|date('Y-m-d') }}
查看更多
看我几分像从前
3楼-- · 2019-08-15 08:34

You can extend twig to generate it for you :

$function = new Twig_SimpleFunction('random_date', function() {
    return mt_rand(time(), time() + 31556926);
});
$twig = new Twig_Environment($loader);
$twig->addFunction($function);

And then you can use it in twig like this :

{{ random_date()|date('d-m-Y') }}
查看更多
放荡不羁爱自由
4楼-- · 2019-08-15 08:50
<!DOCTYPE html>
<html>
<body>

<p>Click the button to display a random number.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
var d = new Date(Math.floor(Math.random()*1E16));
    document.getElementById("demo").innerHTML = d;
}
</script>

</body>
</html>
查看更多
登录 后发表回答