![](https://dzone.com/storage/temp/14699860-pexels-photo-2004161.jpeg)
Last week's article received a comment on a private Facebook group that amounted to "just use JavaScript's built-in formatting." So what would that look like?
#!/usr/bin/env perl
use :: - ;
use ;
'/' =>
sub ($c) { $c-> ( => 'index', => -> ) };
=> sub ( $c, $date = -> , $style = 'full' ) {
my $date_params = join ',' => $date-> , $date-> , $date-> ;
return
qq<new Date($date_params).toLocaleString( [], {dateStyle: "$style"})>;
};
-> ;
__DATA__
@@ index.html.ep
% layout 'default';
% title 'Today';
<ul>
<li><script>
document.write(<%== localize_date $date %>)
</script></li>
% for my $style ( qw(long medium short) ) {
<li><script>
document.write(<%== localize_date $date, $style %>)
</script></li>
% }
</ul>
@@ layouts/default.html.ep
<!DOCTYPE html>
<html>
<head><title><%= title %></title></head>
<body><%= content %></body>
</html>
It's structured much like the Perl-only solution, with a default "/"
route and a localize_date
Mojolicious helper to do the formatting. I opted to output a piece of JavaScript from the helper on lines 11 through 14 since it could be repeated several times in a document. You could instead declare a function in the default layout's HTML <head>
on line 38 that would receive a date and a formatting style, outputting the resulting formatted date.
Localizing Dates in A Perl Web Application
Thankfully, we have a number of tools to assist us:
- The DateTime::Locale library, which enables our Perl software to represent dates and times globally and contains a catalog of locales. It works with the DateTime library for storing our dates as objects that can be easily manipulated and formatted.
- The HTTP Accept-Language header, which lets a web browser communicate to the server what natural languages and locale variants the user understands.
- The HTTP::AcceptLanguage module, which helps us parse the Accept-Language header and select a compatible locale.
Our sample code uses the Mojolicious framework and is very simple; almost half of it is just HTML web page templates. You could easily adapt it to other frameworks or templating systems.