Sunday, January 20, 2019

Converting string date to date format and use of it in laravel

Though you can store code directly as time stamp in database , but any time you missed it, no worries there are many ways to use those string type of date as real date time formatted date:
here is how i did it for my best practice:

let , you take date store  in database in some  variable say : $date, now to convert it to usable date format:

$date= date('Y-M-D', strtotime($date));

now, $date variable will get date where you can operate any type of date query :
here is small example of query i have used: or also i can say that this query which i am going to show below will also help to convert and format unformated date in proper format :

lets say $item->date carries date from controller to blade template , where i write logic to format the code :

@php
$realdate=$item->date;
$myDateTime = DateTime::createFromFormat('Y-m-d', $realdate);
@endphp


$myDateTime is the perfectly formatted form of the date, now on this formatted date you can do and date operations such as:
{{date_format($myDateTime,'M j, Y')}} //eg: 2019-11-26 to : October 26, 2019
{{date_format($myDateTime,'j')}}//eg: 2019-11-26 to : 26
{{date_format($myDateTime,'M')}}//eg: 2019-11-26 to : October
{{date_format($myDateTime,'y')}}//eg: 2019-11-26 to : 2019

I hope you get this all easily ,






No comments:

Post a Comment