Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the Date and numeric weekday in PHP

i'm developing an application in PHP and I need to use dates and the numeric representation of weekdays.

I've tried the following:

$today = date("Y-m-d");
$number = date('N', strtotime($today));
echo "Today: " . $today . " weekday: " . $number . "<br>";
$today = strtotime($today);
$tomorrow = strtotime($today);
$tomorrow = strtotime("+1 day", $today);
$number2 = date('N', strtotime($tomorrow));
echo "Tomorrow: " . date('Y-m-d', $tomorrow) . " weekday: " . $number2 . "<br>";

Output

Today: 2016-11-11 weekday: 5
Tomorrow: 2016-11-12 weekday: 4

This isn't right because the weekday of tomorrow should be 6 instead of 4.

can someone help me out?

like image 630
Edoardo Avatar asked Nov 11 '16 08:11

Edoardo


People also ask

How do you get the day of the week from a date in php?

Use strtotime() function to get the first day of week using PHP. This function returns the default time variable timestamp and then use date() function to convert timestamp date into understandable date. strtotime() Function: The strtotime() function returns the result in timestamp by parsing the time string.

How can get current date and day in php?

Answer: Use the PHP date() Function You can simply use the PHP date() function to get the current data and time in various format, for example, date('d-m-y h:i:s') , date('d/m/y H:i:s') , and so on.

How can I get current date in YYYY MM DD format in php?

date_default_timezone_set('UTC'); echo "<strong>Display current date dd/mm/yyyy format </strong>". "<br />"; echo date("d/m/Y"). "<br />"; echo "<strong>Display current date mm/dd/yyyy format</strong> "."<br />"; echo date("m/d/Y")."<br />"; echo "<strong>Display current date mm-dd-yyyy format </strong>".


1 Answers

Using DateTime would provide a simple solution

<?php
$date = new DateTime();
echo 'Today: '.$date->format( 'Y-m-d' ) .' weekday '. $date->format( 'N' )."\n";
$date->modify( '+1 days' );
echo 'Tomorrow: '.$date->format( 'Y-m-d' ) .' weekday '. $date->format( 'N' )."\n";

Output

Today: 2016-11-11 weekday 5
Tomorrow: 2016-11-12 weekday 6

However the day numbers are slightly different, the N respresents the weekday number and as you can see Friday (Today) is shown as 5. With that Monday would be 1 and Sunday would be 7.

If you look at the example below you should get the same result

echo date( 'N' );

Output

5

Date Formatting - http://php.net/manual/en/function.date.php

like image 118
Blinkydamo Avatar answered Sep 28 '22 13:09

Blinkydamo