Convert a date to the name of the day of the week

Asked

Viewed 3,330 times

8

I am receiving from my database several dates entered by the user (the field is of the date type (yyyy-mm-dd)). What I want is to take that date and convert it to the name of the week day. For example:

<?php
   $data_da_bd = "2014-08-13";
?>

The result would be: Wednesday.

3 answers

6


PHP has facilities for this.

http://php.net/manual/en/function.strftime.php

Just use the desired Pattern ( in your case, %A ) that the query will return correctly.

Don’t forget to put the Locale correct or will present in another language.

== EDIT ==

Since your date is in String, first it is necessary to convert to time.

You can use the function http://php.net/manual/en/function.strtotime.php

In that case, the end would be

date_default_timezone_set("Europe/Lisbon"); 
$data = "2014-08-09"; 
echo(strftime("%A",strtotime($data));
  • date_default_timezone_set("Europe/Lisbon"); $data = "2014-08-09"; echo(strftime("%A",$data); I tried this and today’s name appears. It does not appear to me according to the date

  • Your date is string. First you need to convert to Date. I will change my answer

  • Thank you, that was the problem.

5

An alternate way to solve the problem is to use the class Intldateformatter to manipulate the date formatted. EEEE in setPattern() means the format of the date in case it is the full day, for other format options check the documentation

<?php
date_default_timezone_set('America/Sao_Paulo');

$data = new DateTime('2012-03-20');
$formatter = new IntlDateFormatter('pt_BR', IntlDateFormatter::FULL, 
                                    IntlDateFormatter::FULL, 
                                    IntlDateFormatter::GREGORIAN);
$formatter->setPattern('EEEE');

echo $data->format('d/m/Y') .' é: '. $formatter->format($data);

Example

That response was based on: php how to format a Given datetime Object considering locale get default

4

Just to complement: you can do this using object orientation or procedurally, and Felipe’s response fit in the latter case. To do so using objects (and the class DateTime PHP), just do it this way:

<?php
$data = new DateTime('2014-08-09', new DateTimeZone('Europe/Lisbon'));
echo $data->format('l');
  • 1

    I tested here, the name came English, the Timezone would be a matter of time, for formatted date and other things would be the locale.

  • @lost Well noticed. In this case you have to use the setlocale before.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.