Django equivalent of PHP's date - php

Does anybody know something similar to function date() from PHP in Django?
I'm starting to learn this nice framework, I'm very happy with it (at the momment) but i haven't found that function

Yes.
date
Formats a date according to the given format.
Uses a similar format as PHP’s date() function (http://php.net/date) with some differences.
For example, you can do:
{{ value|date:"D d M Y" }}
If value is a datetime object (e.g., the result of datetime.datetime.now()), the output will be the string 'Jul 22 2013'.
Documentation:
https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
https://docs.djangoproject.com/en/dev/ref/settings/#date-format
https://docs.djangoproject.com/en/dev/topics/i18n/timezones/#naive-and-aware-datetime-objects

Related

How to change DateTime format to a desired format via Carbon laravel

I'm using laravel 5.5 and Carbon library to write an API.
I store all date and time values in MySQL database as common YYYY-MM-DD HH:MM:SS format.
But on the other hand front-end developer ask me to return all dates as 2017-12-20T20:30:00.000Z. seems that is a common format in JavaScript.
Is there any way to convert all DateTime formatted fields to desired format via laravel or Carbon ?
Update:
First problem is solved but another one is that client want to send date times as same 2017-12-20T20:30:00.000Z for all fields of table. while I should get and save them as common DateTime. What can I do in this case?
Javascript uses ISO 8601 syntax. In PHP, you can use like this:
date('c', strtotime($yourDateTime)); // c is ISO 8601 format
Reference here:
Since the date is casting as Carbon, use format():
$date->format($desiredFormat);
The list of characters for creating $desiredFormat will also be helpful.
Laravel Provide getter and setter method for format Eloquent attribute values
by default laravel return 'dateTime' as carbon instance
so, you can change format in model using getter method
public function getDateTimeAttribute($value)
{
$desiredFormat = "Y-M-d"; //change format as per your requirement
$value->format($desiredFormat);
}
Link for more about getter and setter method
https://laravel.com/docs/5.5/eloquent-mutators
{{ date('M j, Y h:ia', strtotime($created_at)) }}
It gives us like "Dec 30, 2017 16:39am"
You can edit you date time of course(M j, Y h:ia) just google it "php: date - manual"

How to format an UTC date to use the Z (Zulu) zone designator in php?

I need to display and handle UTC dates in the following format:
2013-06-28T22:15:00Z
As this format is part of the ISO8601 standard I have no trouble creating DateTime objects from strings like the one above. However I can't find a clean way (meaning no string manipulations like substr and replace, etc.) to present my DateTime object in the desired format. I tried to tweak the server and php datetime settings, with little success. I always get:
$date->format(DateTime::ISO8601); // gives 2013-06-28T22:15:00+00:00
Is there any date format or configuration setting that will give me the desired string? Or I'll have to append the 'Z' manually to a custom time format?
No, there is no special constant for the desired format. I would use:
$date->format('Y-m-d\TH:i:s\Z');
But you will have to make sure that the times you are using are really UTC to avoid interpretation errors in your application.
If you are using Carbon then the method is:
echo $dt->toIso8601ZuluString();
// 2019-02-01T03:45:27Z
In PHP 8 the format character p was added:
$timestamp = new DateTimeImmutable('2013-06-28T22:15:00Z');
echo $timestamp->format('Y-m-d\TH:i:sp');
// 2013-06-28T22:15:00Z
In order to get the UTC date in the desired format, you can use something like this:
gmdate('Y-m-d\TH:i:s\Z', $date->format('U'));
To do this with the object-oriented style date object you need to first set the timezone to UTC, and then output the date:
function dateTo8601Zulu(\DateTimeInterface $date):string {
return (clone $date)
->setTimezone(new \DateTimeZone('UTC'))
->format('Y-m-d\TH:i:s\Z');
}
Edit: clone object before changing timezone.
Since PHP 7.2 DateTimeInterface::ATOM was introduced in favor of DateTimeInterface::ISO8601, although it still lives on for backward compatability reasons.
Usage
$dateTimeObject->format(DateTimeInterface::ATOM)

How to format a PHP date in .Net DataContractJsonSerializer format?

There is a requirement to send a date inside a JSON post using PHP in this following format
\/Date(410256000000-0800)\/
How do I convert a standard dd-mm-yyyy h:i:s datetime like 01-01-2013 12:00:00 to that format in PHP? Just need to know what values correspond to what in that format, not really look for a stringify things answer.
This should do it:
$dateTime = DateTime::createFromFormat('d-m-Y H:i:s', '01-01-2013 12:00:00');
$requiredJsonFormat = sprintf(
'\/Date(%s%s)\/',
$dateTime->format('U') * 1000,
$dateTime->format('O')
);
echo $requiredJsonFormat; // prints '\/Date(1357038000000+0100)\/'
I leave it up to you to find what the formats U and O do from http://php.net/date.
An alternative would be to use PHP's DOTNET API and use the DataContractJsonSerializer class directly from PHP. However, you'd need .NET installed on the server and using PHP's DOTNET API is rather arcane.
The more interesting part is why you need this format at all. This is explained in a blogpost at http://weblogs.asp.net/bleroy/archive/2008/01/18/dates-and-json.aspx
But because of a strange oversight in the EcmaScript specs, there is no standard way of describing dates in JSON. […] Our current approach is using a small loophole in the JSON specs. In a JSON string literal, you may (or may not) escape some characters. Among those characters, weirdly enough, there is the slash character ('/'). […] The new format is "/Date(1198908717056)/" where the number is again the number of milliseconds since January 1st 1970 UTC […] The point is that this disambiguates a date literal from a string that looks like the same date literal, while remaining pure JSON that will be parsed by any standard JSON parser. Of course, a parser that doesn't know about this convention will just see a string, but parsers that do will be able to parse those as dates without a risk for false positives
We created a package for this: https://github.com/webapix/dot-net-json-date-formatter
It uses a similar approach than the previous answer, tested on PHP versions >= 5.6.
use DateTime;
use DateTimeZone;
use Webapix\DotNetJsonDate\Date;
$date = DateTime::createFromFormat(
'd-m-Y H:i:s',
'01-01-2013 12:00:00',
new DateTimeZone('+0000')
);
Date::toJsonDate($date); // returns '/Date(1357041600000+0000)/'

PHP: strtotime formatting

I am trying to put a readable time and date as part of a file name (in php). I am having all kinds of trouble with this and was hoping someone could help. I have tried several different recommendations that I have read around the internet (plus I read the manual) but I really haven't gotten anything to work right. Right now I have this:
$Time=strtotime("now");
$date=DateTime::createFromFormat('m/d/Y H:i:s', '7/24/2012 14:40:30');
$date_readable=$date->$Timestamp();
At that point I then add $date_readable to a file name. It compiles and runs but it doesn't format the date at all. It still gives it as a timestamp.
Any suggestions on how to make this work?
you can do it with simple date function for example
$time = strtotime("now");
$formatDate = date('F jS, Y h:i:s A', $time);
echo $formatDate;
this will print something like
July 25th, 2012 1:02:29 am
DateTime class is more powerful then using simple date function, as DateTime class offers powerful API's plus it is object oriented. however for simple date conversions i would stick to php's date function. as that could do my purpose.
for more formatting option have a look at this link http://www.php.net/manual/en/function.date.php#refsect1-function.date-parameters

Zend Date giving wrong format for the CONSTANT Zend_Date::DATES

I'm having a problem getting the right date format to be returned from my function. The ZF documentation says if I use the constant "Zend_Date::DATES" or "Zend_Date::DATE_MEDIUM" it should return the date in a format 03.09.2011 for en_us locale Zend Documentation But I'm getting the date returned like this Mar 9, 2011 for both of those constants. However, if I use the "Zend_Date::DATE_SHORT" constant I get 03/09/11 which is exactly what the documentation says it should be. So why do the other two constants give me a different format...is it some catch-all default if something is wrong? I doubt this is a ZF bug because loads of people would have flooded them with the bug, so I'm sure I've just got something wrong, but I can't figure out what it might be and need a little help for anyone interested.
here's my function:
function ZEND_format_date_locale_display($str_date, $lang_LOCALE)
{
include_once $zend_lib_path . '/Zend/Date.php';
$date = new Zend_Date();
$date->set($str_date, 'yyyy-MM-dd');
$date = $date->toString(Zend_Date::DATES, $lang_LOCALE);
return $date;
}
The date comes out of the mysql database like '2011-03-09' for a March 9, 2011 date.
I call the function like this:
ZEND_format_date_locale_display('2011-03-09', 'en_us')
any help or ideas are appreciated. Thanks in advance.
Zend Documentation says that "The example output below reflects localization to Europe/GMT+1 hour (e.g. Germany, Austria, France)". So if you set your locale to e.g. 'de' you should get the expected results.
Why don't you use PHP's inbuilt functions?
You can use strtotime() to convert a date in any readable format into a UNIX timestamp, and then you can use date() to convert this timestamp into any format.
http://php.net/manual/en/function.strtotime.php
http://php.net/manual/en/function.date.php

Categories