Random date in a view with Twig

2019-08-15 07:54发布

问题:

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

回答1:

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') }}


回答2:

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:

<!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>


标签: date random twig