How do I get the current date and time in PHP?
Asked Answered
F

45

1072

Which PHP function can return the current date/time?

Flavia answered 22/1, 2009 at 20:9 Comment(4)
TLDR; $date = date('m/d/Y h:i:s a', time());Imes
looks that we cannot get the time of the system which is visiting the site except using javascript. For PHP we can set a fixed time zone to get the current time of that zone.Basset
@RanaNadeem PHP works also without any web context, so "visiting the site" (better: requesting a resource) is no guaranteed event. Also there's no guarantee a request comes from the device directly - you could talk to a proxy or some other layer between server and end user. HTTP does not know any header (and reason) to automatically send a request header containing the client's time (and zone).Kassia
Modern one-liner: echo (new \DateTime())->format( 'Y-m-d H:i:s' );Delphadelphi
I
730

The time would go by your server time. An easy workaround for this is to manually set the timezone by using date_default_timezone_set before the date() or time() functions are called to.

I'm in Melbourne, Australia so I have something like this:

date_default_timezone_set('Australia/Melbourne');

Or another example is LA - US:

date_default_timezone_set('America/Los_Angeles');

You can also see what timezone the server is currently in via:

date_default_timezone_get();

So something like:

$timezone = date_default_timezone_get();
echo "The current server timezone is: " . $timezone;

So the short answer for your question would be:

// Change the line below to your timezone!
date_default_timezone_set('Australia/Melbourne');
$date = date('m/d/Y h:i:s a', time());

Then all the times would be to the timezone you just set :)

Introrse answered 23/1, 2009 at 0:19 Comment(8)
The call to time() is redundant, date() will automatically use the current time.Abound
Thanks! I was wondering how to change the time zone on the date() function :)Lungfish
@oneofakind America/Los_AngelesPrepositor
OP never asked about timezone. A simpler and more correct answer would simply show server time.Uveitis
@AyexeM I actually appreciated the additional timezone information. It saved me a second search.Weitzman
You can get all the time zone from here Time ZoneCalyces
@AyexeM A simpler and more correct answer would not be to omit potentially important and related information, but instead to answer the question, as you suggest, but then provide additional information on timezones beneath it. There's no need to omit potentially crucial information just because it wasn't asked for.Faitour
after all you want to save date/time in database, if that is what needed; why not just use the MySQL commands to deal with date/time. MySQL provides considerable flexibility in how dates and times are formatted. take this example: INSERT INTO orders (order_item, order_date, order_delivery) VALUES ('iPhone 8Gb', NOW(), DATE_ADD(NOW(), INTERVAL 14 DAY));. See Dates and Times in MySQLLordling
A
651
// Simply:
$date = date('Y-m-d H:i:s');

// Or:
$date = date('Y/m/d H:i:s');

// This would return the date in the following formats respectively:
$date = '2012-03-06 17:33:07';
// Or
$date = '2012/03/06 17:33:07';

/** 
 * This time is based on the default server time zone.
 * If you want the date in a different time zone,
 * say if you come from Nairobi, Kenya like I do, you can set
 * the time zone to Nairobi as shown below.
 */

date_default_timezone_set('Africa/Nairobi');

// Then call the date functions
$date = date('Y-m-d H:i:s');
// Or
$date = date('Y/m/d H:i:s');

// date_default_timezone_set() function is however
// supported by PHP version 5.1.0 or above.

For a time-zone reference, see List of Supported Timezones.

Aspasia answered 6/3, 2012 at 14:42 Comment(2)
This is a much more straight-forward answer than the top one. Thanks!Rawalpindi
Thank you for the link of supported timezones, i was about to google it :)Becquerel
W
265

Since PHP 5.2.0 you can use the DateTime() class:

use \Datetime;

$now = new DateTime();
echo $now->format('Y-m-d H:i:s');    // MySQL datetime format
echo $now->getTimestamp();           // Unix Timestamp -- Since PHP 5.3

And to specify the timezone:

$now = new DateTime(null, new DateTimeZone('America/New_York'));
$now->setTimezone(new DateTimeZone('Europe/London'));    // Another way
echo $now->getTimezone();
Wardle answered 29/5, 2013 at 12:44 Comment(2)
yes, here are my used case : $history = History::getLastChange($id_att); $dt = new DateTime($history['action_datetime']); $dt->setTimezone(new DateTimeZone('Europe/Paris')); if ($history) echo "<p><i>Dernière modification par " . $history['author']. ", le " . $dt->format('Y-m-d H:i:s') . "</i></p>";Kuvasz
One-liner: echo (new \DateTime())->format( 'Y-m-d H:i:s' );Delphadelphi
D
118

Reference: Here's a link

This can be more reliable than simply adding or subtracting the number of seconds in a day or a month to a timestamp because of daylight saving time.

The PHP code

// Assuming today is March 10th, 2001, 5:16:18 pm, and that we are in the
// Mountain Standard Time (MST) Time Zone

$today = date("F j, Y, g:i a");                 // March 10, 2001, 5:16 pm
$today = date("m.d.y");                         // 03.10.01
$today = date("j, n, Y");                       // 10, 3, 2001
$today = date("Ymd");                           // 20010310
$today = date('h-i-s, j-m-y, it is w Day');     // 05-16-18, 10-03-01, 1631 1618 6 Satpm01
$today = date('\i\t \i\s \t\h\e jS \d\a\y.');   // it is the 10th day.
$today = date("D M j G:i:s T Y");               // Sat Mar 10 17:16:18 MST 2001
$today = date('H:m:s \m \i\s\ \m\o\n\t\h');     // 17:03:18 m is month
$today = date("H:i:s");                         // 17:16:18
$today = date("Y-m-d H:i:s");                   // 2001-03-10 17:16:18 (the MySQL DATETIME format)
Doorway answered 29/8, 2013 at 18:49 Comment(0)
E
78

PHP's time() returns a current Unix timestamp. With this, you can use the date() function to format it to your needs.

$date = date('Format String', time());

As Paolo mentioned in the comments, the second argument is redundant. The following snippet is equivalent to the one above:

$date = date('Format String');
Extrauterine answered 22/1, 2009 at 20:13 Comment(1)
the 2nd argument of the date function is assumed to be time() if left empty.Turmel
P
75

You can either use the $_SERVER['REQUEST_TIME'] variable (available since PHP 5.1.0) or the time() function to get the current Unix timestamp.

Pinsky answered 22/1, 2009 at 20:11 Comment(2)
It's worth noting that the timestamp returned by the time() function is independent of the timezone. (So calling date_default_timezone_set("your-particular-timezone"); before will have no effect.)Involucrum
@Involucrum - not certain what you mean by "independent of the time zone"; it's "dependent" on the time zone the server is set to? You can have a server on the east coast set to a time zone on the west coast or vice versa.Hyozo
A
67

You can use both the $_SERVER['REQUEST_TIME'] variable or the time() function. Both of these return a Unix timestamp.

Most of the time these two solutions will yield the exact same Unix Timestamp. The difference between these is that $_SERVER['REQUEST_TIME'] returns the time stamp of the most recent server request and time() returns the current time. This may create minor differences in accuracy depending on your application, but for most cases both of these solutions should suffice.

Based on your example code above, you are going to want to format this information once you obtain the Unix Timestamp. Unformatted Unix time looks like: 1232659628

So in order to get something that will work, you can use the date() function to format it.

A good reference for ways to use the date() function is located in the PHP Manual.

As an example, the following code returns a date that looks like this: 01/22/2009 04:35:00 pm :

echo date("m/d/Y h:i:s a", time());
Amphipod answered 22/1, 2009 at 21:36 Comment(2)
How does different web servers handle $_SERVER['REQUEST_TIME'] ?Burden
Best answer hands down. You even add how to get from UNIX timestamp to normal person date which is greatly appreciatedPanaggio
D
47

PHP's date function can do this job.

date()

Description:

string date(string $format [, int $timestamp = time()])

Returns a string formatted according to the given format string using the given integer timestamp or the current time if no timestamp is given.

Examples:

$today = date("F j, Y, g:i a");               // March 10, 2001, 5:16 pm
$today = date("m.d.y");                       // 03.10.01
$today = date("j, n, Y");                     // 10, 3, 2001
$today = date("Ymd");                         // 20010310
$today = date('h-i-s, j-m-y, it is w Day');   // 05-16-18, 10-03-01, 1631 1618 6 Satpm01
$today = date('\i\t \i\s \t\h\e jS \d\a\y.'); // it is the 10th day.
$today = date("D M j G:i:s T Y");             // Sat Mar 10 17:16:18 MST 2001
$today = date('H:m:s \m \i\s\ \m\o\n\t\h');   // 17:03:18 m is month
$today = date("H:i:s");                       // 17:16:18
$today = date("Y-m-d H:i:s");                 // 2001-03-10 17:16:18 (the MySQL DATETIME format)
Destructible answered 17/4, 2015 at 11:43 Comment(0)
S
34

For the new PHP programmer might confuse why there are lot of method for to get current date and time and which one to use in their project.

1. date method (PHP 4, PHP 5, PHP 7)

This is the very common and very easiest way to get the date and time in php.

// set the default timezone to use. Available since PHP 5.1
date_default_timezone_set('UTC');


// Prints something like: Monday
echo date("l");

// Prints something like: Monday 8th of August 2005 03:12:46 PM
echo date('l jS \of F Y h:i:s A');

// Prints: July 1, 2000 is on a Saturday
echo "July 1, 2000 is on a " . date("l", mktime(0, 0, 0, 7, 1, 2000));

/* use the constants in the format parameter */
// prints something like: Wed, 25 Sep 2013 15:28:57 -0700
echo date(DATE_RFC2822);

// prints something like: 2000-07-01T00:00:00+00:00
echo date(DATE_ATOM, mktime(0, 0, 0, 7, 1, 2000));

You can learn more about it in here

2. DateTime class (PHP 5 >= 5.2.0, PHP 7)

when you want to use PHP with OOP, this is the best way to get date and time.

<?php
// Specified date/time in your computer's time zone.
$date = new DateTime('2000-01-01');
echo $date->format('Y-m-d H:i:sP') . "\n";

// Specified date/time in the specified time zone.
$date = new DateTime('2000-01-01', new DateTimeZone('Pacific/Nauru'));
echo $date->format('Y-m-d H:i:sP') . "\n";

// Current date/time in your computer's time zone.
$date = new DateTime();
echo $date->format('Y-m-d H:i:sP') . "\n";

// Current date/time in the specified time zone.
$date = new DateTime(null, new DateTimeZone('Pacific/Nauru'));
echo $date->format('Y-m-d H:i:sP') . "\n";

// Using a UNIX timestamp.  Notice the result is in the UTC time zone.
$date = new DateTime('@946684800');
echo $date->format('Y-m-d H:i:sP') . "\n";

// Non-existent values roll over.
$date = new DateTime('2000-02-30');
echo $date->format('Y-m-d H:i:sP') . "\n";
?>

You can learn more about it in here

3. Carbon Date time package

if you are using Composer, Laravel, Symfony or any kinda framework this is the best way to get the date and time. Also this package extends DateTime class in php so you use all the method in Datetime class. This in-built in frameworks like laravel so you don't have to install it separately.

printf("Right now is %s", Carbon::now()->toDateTimeString());
printf("Right now in Vancouver is %s", Carbon::now('America/Vancouver')); // automatically converted to string
$tomorrow = Carbon::now()->addDay();
$lastWeek = Carbon::now()->subWeek();

// Carbon embed 823 languages:
echo $tomorrow->locale('fr')->isoFormat('dddd, MMMM Do YYYY, h:mm');
echo $tomorrow->locale('ar')->isoFormat('dddd, MMMM Do YYYY, h:mm');

$officialDate = Carbon::now()->toRfc2822String();

$howOldAmI = Carbon::createFromDate(1975, 5, 21)->age;

$noonTodayLondonTime = Carbon::createFromTime(12, 0, 0, 'Europe/London');

$internetWillBlowUpOn = Carbon::create(2038, 01, 19, 3, 14, 7, 'GMT');

if (Carbon::now()->isWeekend()) {
    echo 'Party!';
}
echo Carbon::now()->subMinutes(2)->diffForHumans(); // '2 minutes ago'

You can learn more about it in here

Hope this helps and if you know any other way to get the date and time feel free to edit the answer.

Stereotomy answered 15/6, 2019 at 17:45 Comment(3)
I liked some other answers which show how to format the string even with custom text, or let's say what format is best for MySQL etc, but I would definitely accept this one for showing all three types and usages: procedural, object oriented and OOP framework.Gablet
@Gablet I could've answered something like that but the question is "How do I get the current date and time in PHP?", our main focus should be on the question. :)Stereotomy
date is good for a quick 'n' dirty way to get the date in string format, but for any serious datetime manipulation, imo one should always resort to DateTime for consistency, reliability, and for less errors :)Henderson
F
29

Use:

$date = date('m/d/Y h:i:s a', time());

It works.

Flavia answered 22/1, 2009 at 22:32 Comment(6)
What I mean is the time comes back EST when I'm PST... but why? Is it the server time and the server is EST? Can I get users time? Their server may be another time zone, no?Flavia
The date function is the time of your server, either check it, or temporarily set it /w PHP before you run date.Brigette
thanks, my service must not be up to date with php because O works for GMT but not P or "e" time zone... thanks!!Flavia
This $date = date('m/d/Y h:i:s a', time()); gets the server date but still doesn't get me the user date. This is showing me at EST when I'm at PST. I want to get the date the user sends the form and like me their server may be in a different time zone.Flavia
Actually now that I think about it the time isn't as important as the date. THANKS TO ALL!!Flavia
I think the user's time would need to be obtained using Javascript since PHP runs on your web server and Javascript runs on their computer.Stilted
D
28

its very simple

echo $date = date('Y-m-d H:i:s');

Dymoke answered 18/3, 2017 at 11:12 Comment(0)
Z
27
 $date = new DateTime('now', new DateTimeZone('Asia/Kolkata'));
 echo $date->format('d-m-Y H:i:s');

Update

 //Also get am/pm in datetime:
 echo $date->format('d-m-Y H:i:s a'); // output 30-12-2013 10:16:15 am

For the date format, PHP date() Function is useful.

Zacynthus answered 7/6, 2013 at 9:59 Comment(0)
K
18
echo date("d-m-Y H:i:sa");

This code will get the date and time of the server that the code runs on.

Karissakarita answered 28/3, 2017 at 10:13 Comment(4)
Downvoted for misleading answer. No, it won't get the time of your local machine, unless you are running the server locally as well. It will get the date and time of the server.Eyeless
@Eyeless - "This code will get the date and time of the "server" he said nothing about the "local machine" you said that. You don't have to be running your server "locally" either - you can have a server anywhere in the world set to whatever time zone you want. Your down vote was dead wrong and for no reasonHyozo
@NealDavis Did you think to look at the edit? I posted that comment, suggested an edit on the incorrect information, and in the meantime waited for it to be approved. Now it's approved and showing the correct information.Eyeless
@NealDavis Additionally if you bothered to read the original post, it literally said "This code will get the date and time of your local machine (PC).". That's utterly misleading.Eyeless
L
16

You can use this format also:

$date = date("d-m-Y");

Or

$date = date("Y-m-d H:i:s");
Longship answered 12/10, 2016 at 7:2 Comment(0)
T
15

According to the article How to Get Current Datetime (NOW) with PHP, there are two common ways to get the current date. To get current datetime (now) with PHP, you can use the date class with any PHP version, or better the datetime class with PHP >= 5.2.

Various date format expressions are available here.

Example using date

This expression will return NOW in format Y-m-d H:i:s.

<?php
    echo date('Y-m-d H:i:s');
?>

Example using datetime class

This expression will return NOW in format Y-m-d H:i:s.

<?php
    $dt = new DateTime();
    echo $dt->format('Y-m-d H:i:s');
?>
Taciturnity answered 26/9, 2013 at 4:28 Comment(0)
H
14
<?php
// Assuming today is March 10th, 2001, 5:16:18 pm, and that we are in the
// Mountain Standard Time (MST) Time Zone

$today = date("F j, Y, g:i a");                 // March 10, 2001, 5:16 pm
$today = date("m.d.y");                         // 03.10.01
$today = date("j, n, Y");                       // 10, 3, 2001
$today = date("Ymd");                           // 20010310
$today = date('h-i-s, j-m-y, it is w Day');     // 05-16-18, 10-03-01, 1631 1618 6 Satpm01
$today = date('\i\t \i\s \t\h\e jS \d\a\y.');   // it is the 10th day.
$today = date("D M j G:i:s T Y");               // Sat Mar 10 17:16:18 MST 2001
$today = date('H:m:s \m \i\s\ \m\o\n\t\h');     // 17:03:18 m is month
$today = date("H:i:s");                         // 17:16:18
$today = date("Y-m-d H:i:s");                   // 2001-03-10 17:16:18 (the MySQL DATETIME format)
?>
Hollingsworth answered 19/1, 2017 at 9:7 Comment(0)
D
13
<?php
echo "<b>".date('l\, F jS\, Y ')."</b>";
?>

Prints like this

Sunday, December 9th, 2012

Dorcia answered 9/12, 2012 at 8:46 Comment(0)
C
12
date(format, timestamp)

The date function returns a string formatted according to the given format string using the given integer timestamp or the current time if no timestamp is given. In other words, timestamp is optional and defaults to the value of time().

And the parameters are -

format - Required. Specifies the format of the timestamp

timestamp - (Optional) Specifies a timestamp. Default is the current date and time

How to get a simple date

The required format parameter of the date() function specifies how to format the date (or time).

Here are some characters that are commonly used for dates:

  1. d - Represents the day of the month (01 to 31)
  2. m - Represents a month (01 to 12)
  3. Y - Represents a year (in four digits)
  4. l (lowercase 'L') - Represents the day of the week

Other characters, like "/", ".", or "-" can also be inserted between the characters to add additional formatting.

The example below formats today's date in three different ways:

<?php
    echo "Today is " . date("Y/m/d") . "<br>";
    echo "Today is " . date("Y.m.d") . "<br>";
    echo "Today is " . date("Y-m-d") . "<br>";
    echo "Today is " . date("l");
?>

Some useful links

Caldwell answered 14/3, 2016 at 6:43 Comment(0)
N
11

Set your time zone:

date_default_timezone_set('Asia/Calcutta');

Then call the date functions

$date = date('Y-m-d H:i:s');
Neomaneomah answered 11/4, 2014 at 7:14 Comment(0)
C
11

The date format depends too:

echo date("d/m/Y H:i:sa"); // 13/04/2017 19:38:15pm
Carrasco answered 14/4, 2017 at 0:44 Comment(1)
This is hardly comprehensible. Can you elaborate?Ancilin
D
11

Very simple

date_default_timezone_set('Asia/Kolkata');
$date = date('m/d/Y H:i:s', time());
Descendant answered 1/4, 2019 at 12:28 Comment(1)
I haven't seen that.Descendant
H
10
date_default_timezone_set('Europe/Warsaw');
echo("<p class='time'>".date('H:i:s')."</p>");
echo("<p class='date'>".date('d/m/Y')."</p>");
Holbein answered 22/1, 2009 at 20:9 Comment(0)
S
10

If you want a different timescale, please use:

$tomorrow  = mktime(0, 0, 0, date("m")  , date("d")+1, date("Y"));
$lastmonth = mktime(0, 0, 0, date("m")-1, date("d"),   date("Y"));
$nextyear  = mktime(0, 0, 0, date("m"),   date("d"),   date("Y")+1);

date_default_timezone_set("Asia/Calcutta");
echo date("Y/m/d H:i:s");
Siloa answered 1/2, 2014 at 11:55 Comment(3)
What do you mean by "timescale"?Ancilin
"timezone", probably.Knepper
I believe @Jaymin may mean if you want to adjust the time ahead a day, back a month, etc.Wame
D
10

You can use this code:

<?php
    $currentDateTime = date('Y-m-d H:i:s');
    echo $currentDateTime;
?>
Dust answered 19/6, 2017 at 8:4 Comment(0)
P
9

I found that the simplest way of getting the current time in PHP is something like this.

//Prints out something like 10:00am Just be sure to set your timezone correctly.
date_default_timezone_set("America/Chicago");
$TIME = date('G:ia'); 
Playa answered 19/10, 2012 at 14:13 Comment(0)
W
8

Another simple way is to take the timestamp of the current date and time. Use mktime() function:

$now = mktime(); // Return timestamp of the current time

Then you can convert this to another date format:

//// Prints something like: Thursday 26th of January 2017 01:12:36 PM
echo date('l jS \of F Y h:i:s A',$now);

More date formats are here: http://php.net/manual/en/function.date.php

Windburn answered 26/1, 2017 at 11:13 Comment(0)
J
8

The best way to get the current time and date is by the date function in PHP:

$date = date('FORMAT'); // FORMAT E.g.: Y-m-d H:i:s

$current_date = date('Y-m-d H:i:s');

With the Unix timestamp:

$now_date = date('FORMAT', time()); // FORMAT Eg : Y-m-d H:i:s

To set the server time zone:

date_default_timezone_set('Asia/Calcutta');

A different time zone list is here.

Josphinejoss answered 14/3, 2018 at 7:19 Comment(0)
R
8

You can simply use this code to get the current date and time

echo date('r', time());

or using this for more customizable.

echo date('Y-m-d H:i:s');
Rattray answered 14/11, 2019 at 7:50 Comment(0)
M
8

Your Country Time Zone: List of Supported Timezones

date_default_timezone_set('Asia/Kolkata');

$dateYmd = date('Y-m-d');
echo "Current Year Month Day: $dateYmd";

Current Year Month Day: 2022-01-03

$datehms = date('h:i:s');
echo "Current Hour Minute Second: $datehms";

Current Hour Minute Second: 11:05:38

Melicent answered 3/1, 2022 at 17:6 Comment(0)
P
6

If you are Bangladeshi, and if you want to get the time of Dhaka then use this:

$date = new DateTime();
$date->setTimeZone(new DateTimeZone("Asia/Dhaka"));
$get_datetime = $date->format('d.m.Y H:i:s');
Possession answered 15/3, 2017 at 9:52 Comment(0)
M
6

Normally, this function for date is useful for everyone: date("Y/m/d");

But time is something different, because the time function depends on either the PHP version or system date.

So probably use it like this to get our own time zone:

$date = new DateTime('now', new DateTimeZone('Asia/Kolkata'));
echo $date->format('H:m:s');

This function shows the 24 hours time.

Messy answered 3/7, 2018 at 9:52 Comment(1)
it set the date to 1970 for me !Evident
J
6
echo date('y-m-d'); // Today

This will return today's date.

Junco answered 27/2, 2019 at 4:13 Comment(0)
R
6

Here are some characters that are commonly used for times:

  • d - Represents the day of the month (01 to 31)

  • m - Represents a month (01 to 12)

  • Y - Represents a year (in four digits)

  • l (lowercase 'L') - Represents the day of the week

  • H - 24-hour format of an hour (00 to 23)

  • h - 12-hour format of an hour with leading zeros (01 to 12)

  • i - Minutes with leading zeros (00 to 59)

  • s - Seconds with leading zeros (00 to 59)

  • a - Lowercase Ante meridiem and Post meridiem (am or pm)

example :

echo "Today " . date("Y/m/d") ;
echo "time " . date("h:i:sa");
Radioactivate answered 19/11, 2020 at 13:42 Comment(0)
O
5
// Set the default timezone to use. Available since PHP 5.1
date_default_timezone_set('UTC');


// Prints something like: Monday
echo date("l");

// Prints something like: Monday 8th of August 2016 03:12:46 PM
echo date('l jS \of F Y h:i:s A');

// Prints: July 1, 2016 is on a Saturday
echo "July 1, 2016 is on a " . date("l", mktime(0, 0, 0, 7, 1, 2016));

/* Use the constants in the format parameter */
// Prints something like: Wed, 25 Sep 2013 15:28:57 -0700
echo date(DATE_RFC2822);

// Prints something like: 2016-07-01T00:00:00+00:00
echo date(DATE_ATOM, mktime(0, 0, 0, 7, 1, 2000));
Obit answered 19/8, 2015 at 23:57 Comment(0)
P
5

Here are some characters that are commonly used for times:

  1. h - 12-hour format of an hour with leading zeros (01 to 12)
  2. i - Minutes with leading zeros (00 to 59)
  3. s - Seconds with leading zeros (00 to 59)
  4. a - Lowercase Ante meridiem and Post meridiem (am or pm)

Get your time zone

<?php
    date_default_timezone_set("America/New_York");
    echo "The time is " . date("h:i:sa");
?>

Check this out (optional)

<?php
    $d = mktime(11, 14, 54, 8, 12, 2014);
    echo "Created date is " . date("Y-m-d h:i:sa", $d);
?>

For date

<?php
    echo "Today is " . date("Y/m/d") . ;
    echo "Today is " . date("Y.m.d") . ;
    echo "Today is " . date("Y-m-d") . ;
    echo "Today is " . date("l");
?>

Here are some characters that are commonly used for dates:

  1. d - Represents the day of the month (01 to 31)
  2. m - Represents a month (01 to 12)
  3. Y - Represents a year (in four digits)
  4. l (lowercase 'L') - Represents the day of the week

Source-W3-Schools

Penniepenniless answered 29/8, 2017 at 13:24 Comment(2)
What is the purpose of the trailing . in date("Y/m/d") . ;?Ancilin
To concatenate another string or variable I guess. Thank you for your edits. :-)Penniepenniless
F
5

simply use: date("Y-m-d H:i:s") this will give you your date and time like '2020-08-22 12:20:30' this . add date_default_timezone_set("your time zone") before date() function to get the time date of your area/zone. here you can find you time zone

Fryer answered 24/8, 2020 at 6:25 Comment(2)
You're printing month twice, one time where it should and another - where minute goes!Jus
I am trying to use date('Y-m-d'); but for some reason the year is subtracted from month and further with date. hence the output of today's date is (2020-11-19=1990)Correct
C
4

If you want to get the date like 12-3-2016, separate each day, month, and year value, then copy-paste this code:

$day = date("d");
$month = date("m");
$year = date("y");
print "date" . $day . "-" . $month . "-" . $year;
Complot answered 12/3, 2016 at 10:35 Comment(0)
A
4

We can use the date function and set the default timezone:

<?php
    date_default_timezone_set("Asia/Kolkata");
    echo "Today is " . date("Y/m/d") . "<br>";
    echo "Today is " . date("Y.m.d") . "<br>";
    echo "Today is " . date("Y-m-d") . "<br>";
    echo "Today is " . date("l");
    echo "The time is " . date("h:i:sa");
?>
Apterous answered 27/12, 2017 at 11:32 Comment(0)
I
3

PHP returns the current time in seconds. You need to format them in whatever format you want.

<?php
    // time() returns current time in seconds
    $in_seconds = time();

    // strftime - Format a local time/date according to locale settings
    echo strftime("%m/%d/%y", $in_seconds);
?>

Reference: https://www.php.net/manual/en/function.strftime.php

Inevasible answered 9/12, 2016 at 20:24 Comment(0)
I
2

You can do:

$now = strtotime(date('Y-m-d H:i:s')); // = Now 

See docs for full formatting options: https://www.php.net/manual/en/function.date.php

Impulsion answered 26/10, 2022 at 15:10 Comment(1)
This is nonsense, because one can call time() directly to get the timestamp. date() does implicitly call time() already but returns text, and strtotime() converts text into a timestamp.Kassia
G
1

Linux server time and PHP time() difference time zone as follows:

<?php
    putenv("TZ=Asia/Kabul");
    $t = time();
    echo date('d/m/Y H:i:sa', $t);
?>
Girth answered 13/6, 2018 at 9:20 Comment(0)
M
1

Use date() and DateTimeInterface::format to format a date, i.e., date('Y-m-d H:i:s');, and you have these as your optional formatting:

Source: DateTimeInterface:::format page.

format character Description Example returned values
Day --- ---
d Day of the month, 2 digits with leading zeros 01 to 31
D A textual representation of a day, three letters Mon through Sun
j Day of the month without leading zeros 1 to 31
l (lowercase 'L') A full textual representation of the day of the week Sunday through Saturday
N ISO 8601 numeric representation of the day of the week 1 (for Monday) through 7 (for Sunday)
S English ordinal suffix for the day of the month, 2 characters st, nd, rd or th. Works well with j
w Numeric representation of the day of the week 0 (for Sunday) through 6 (for Saturday)
z The day of the year (starting from 0) 0 through 365
Week --- ---
W ISO 8601 week number of year, weeks starting on Monday Example: 42 (the 42nd week in the year)
Month --- ---
F A full textual representation of a month, such as January or March January through December
m Numeric representation of a month, with leading zeros 01 through 12
M A short textual representation of a month, three letters Jan through Dec
n Numeric representation of a month, without leading zeros 1 through 12
t Number of days in the given month 28 through 31
Year --- ---
L Whether it's a leap year 1 if it is a leap year, 0 otherwise.
o ISO 8601 week-numbering year. This has the same value as Y, except that if the ISO week number (W) belongs to the previous or next year, that year is used instead. Examples: 1999 or 2003
X An expanded full numeric representation of a year, at least 4 digits, with - for years BCE, and + for years CE. Examples: -0055, +0787, +1999, +10191
x An expanded full numeric representation if requried, or a standard full numeral representation if possible (like Y). At least four digits. Years BCE are prefixed with a -. Years beyond (and including) 10000 are prefixed by a +. Examples: -0055, 0787, 1999, +10191
Y A full numeric representation of a year, at least 4 digits, with - for years BCE. Examples: -0055, 0787, 1999, 2003, 10191
y A two digit representation of a year Examples: 99 or 03
Time --- ---
a Lowercase Ante meridiem and Post meridiem am or pm
A Uppercase Ante meridiem and Post meridiem AM or PM
B Swatch Internet time 000 through 999
g 12-hour format of an hour without leading zeros 1 through 12
G 24-hour format of an hour without leading zeros 0 through 23
h 12-hour format of an hour with leading zeros 01 through 12
H 24-hour format of an hour with leading zeros 00 through 23
i Minutes with leading zeros 00 to 59
s Seconds with leading zeros 00 through 59
u Microseconds. Note that date() will always generate 000000 since it takes an int parameter, whereas DateTime::format() does support microseconds if DateTime was created with microseconds. Example: 654321
v Milliseconds. Same note applies as for u. Example: 654
Timezone --- ---
e Timezone identifier Examples: UTC, GMT, Atlantic/Azores
I (capital i) Whether or not the date is in daylight saving time 1 if Daylight Saving Time, 0 otherwise.
O Difference to Greenwich time (GMT) without colon between hours and minutes Example: +0200
P Difference to Greenwich time (GMT) with colon between hours and minutes Example: +02:00
p The same as P, but returns Z instead of +00:00 (available as of PHP 8.0.0) Examples: Z or +02:00
T Timezone abbreviation, if known; otherwise the GMT offset. Examples: EST, MDT, +05
Z Timezone offset in seconds. The offset for timezones west of UTC is always negative, and for those east of UTC is always positive. -43200 through 50400
Full Date/Time --- ---
c ISO 8601 date 2004-02-12T15:19:21+00:00
r » RFC 2822/» RFC 5322 formatted date Example: Thu, 21 Dec 2000 16:01:07 +0200
U Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT) See also time()
Minstrelsy answered 9/11, 2022 at 18:56 Comment(0)
F
1

A modern one-liner would be with the DateTime object:

echo (new DateTime('now', new DateTimeZone('Europe/Warsaw')))->format('d-m-Y H:i:s');
Floriaflorian answered 21/11, 2023 at 11:2 Comment(0)
H
1

For those coming from Javascript background, here's how to get the data from DateTime object:

Javascript PHP
console.log( new Date() ) echo (new DateTime())->format( DateTime::RSS )
or print_r( new DateTime() ) (quick glance)
(new Date())->getTime() / (new Date())->now() (new DateTime())->getTimestamp()
(new Date()).toUTCString() ( new DateTime('now', new DateTimeZone('UTC') ) )->format( DateTime::RSS )
(new Date()).toISOString() (new DateTime())->format( DateTime::ATOM )
new Date('01 Jan 1970 00:00:00 GMT') new DateTime('01 Jan 1970 00:00:00 GMT')
dateObj.getDate() $dateTimeObj->format('j')
dateObj.getMonth() (0-11) $dateTimeObj->format('n') (1-12)
dateObj.getFullYear() (1-4 digits) $dateTimeObj->format('Y') (4+ digits)
dateObj.getHours() (0-23) $dateTimeObj->format('H') (00-23)
dateObj.getMinutes() (0-59) $dateTimeObj->format('i') (00-59)
dateObj.getSeconds() (0-59) $dateTimeObj->format('s') (00-59)
dateObj.getMilliseconds() (0-999) $dateTimeObj->format('v') (000-999)
Henderson answered 29/12, 2023 at 2:3 Comment(0)
A
0

getting current date in PHP:

Date:

<?php
$currentDate = date("Y-m-d"); // Returns the current date in the format "YYYY-MM-DD"
echo $currentDate;
?>

Datetime:

<?php
$currentDateTime = date("Y-m-d H:i:s");
echo $currentDateTime;
?>

getting current date in Laravel(Carbon library):

use Carbon\Carbon;

$currentDate = Carbon::now();
$formattedDate = $currentDate->format('Y-m-d');
echo $formattedDate;
Alteration answered 8/1 at 12:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.