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