Stop CodeIgniter Model to format SQL Date fields - codeigniter

I have an MSSQL Database table with Date field. When selecting that field with codeigniter, it returns a formatted date different from the format found in the database. What I need is for the CI model to return the original date format so I can format the date as I needed.
TSQL returns
2018-05-18
Displayed as HTML
May 18, 2018 12:00:00:AM
I need to display as is
2018-05-18

Hope this will help you :
$returned_date ='May 18, 2018 12:00:00:AM';
$date = DateTime::createFromFormat('M d, Y H:i:s:A', $returned_date);
echo $date->format('Y-m-d');
/*Output 2018-05-18*/
Working example : https://eval.in/1005671
For more : http://php.net/manual/en/datetime.createfromformat.php

When you are displaying it on your html/php please use below code to format your date string:
$newDate = date("Y-m-d", strtotime($originalDate));

Related

Change timezone with Carbon

I have a date that is coming from database (type date):
2018-08-25
This date is in french timezone.
When I do:
$from = Carbon::parse("2018-08-25", 'Europe/Paris');
$from->timezone('UTC');
dd($from);
I get:
date: 2018-08-24 22:00:00.0 UTC (+00:00)
Which is what I want
But when I use field from DB:
$operation = Operation::findOrFail($request->operation);
$from = Carbon::parse($operation->date_ini, 'Europe/Paris');
$from->timezone('UTC');
dd($from);
I get:
date: 2018-08-25 00:00:00.0 UTC (+00:00)
In my DB, field is saved as : 2018-08-25, so literraly, it means 2018-08-25 UTC. So result is coherent. But I'm not sure how to deal with it to get what I want. The implication would be that I have to store my date like a datetime in DB so that I can store it in UTC with 1 or 2 hours less. Is there anyway to avoid this and keep it simple ?
Any idea ?
I solved it using:
$from = Carbon::parse($operation->date_ini)->shiftTimezone('Europe/Paris');;
shiftTimezone with change timezone without changing the date. So, it do the trick for me !
If you call setTimezone() on an existing instance of Carbon, it will change the date/time to the new timezone, for example
$changeTimeZone = \Carbon\Carbon::parse($operation->date_ini)->setTimezone('Asia/Dhaka')->format('H:i');

Double time specification in file in laravel api

I am making api's in laravel and getting 2021-01-30T10:30:17.704 05:30 from $request->followup and i have column in database named followup having datetime datatype. But it's giving me following error.
Carbon\Exceptions\InvalidFormatException: Could not parse '2021-01-30T10:30:17.704 05:30': DateTime::__construct(): Failed to parse time string (2021-01-30T10:30:17.704 05:30) at position 24 (0): Double time specification in file D:\xampp2\htdocs\synocrm-baid\rest-apis\vendor\nesbot\carbon\src\Carbon\Traits\Creator.php on line 188
I tried to change format like
$followupDate = date('Y-m-d h:i:s A',strtotime($request->followup));
My modal having
#property Carbon|null $followup
$request->followup is appending datetime with datetime
Original Value: 2021-01-30T10:30:17.704 05:30
Datetime: 2021-01-30T10:30:17.704
Time: 05:30
As we can see, there is two Time (05:30 and 10:30:17), because of which the strtotime() cannot convert the value.
In order to fix the problem,
Send the value as time time only (2021-01-30T10:30:17.704) instead of two times Time attribute
If you have no control over request value, you can retrieve only date value like:
$dateValue = explode(' ', $request->followup)[0];
$followupDate = date('Y-m-d h:i:s A',strtotime($dateValue));
Or Using Carbon
$followupDate = Carbon::parse($dateValue);
I would not recommend option 2 because it creates problems and confusion for other devs.
2021-01-30T10:30:17.704 05:30
It does not seem to valid timestamp. For parsing, it should be the valid timestamp or date.

D3 Date Parse Using Time Format

I am new to D3.js. I have a date string like "01 DEC 2017". I need to fetch year from it. I am using time format. It's returning null. What is wrong in my code ? Advance thanks for any help.
My code :
d.date = d3.time.format("%Y-%m-%d").parse("01 DEC 2017").getFullYear();

Fill new column with data modified manipulated from data in pre-existing data in another row in Laravel

I have a pre-existing application built with a huge database. In this database, there's a column expires_in that holds a date but the date is saved in this format:
02 Mar 2018 ( i.e. 'd M Y' format)
I want to copy this data into a new column where it will be saved as date in expiration_date column (like this: 2018-03-02 ).
I want to do this in the most efficient way because the database has thousands of records.
Thank you.
Use QueryBuilder's chunk method -- this fetches small subsets of data in a loop. Otherwise with thousands of records, your request could timeout or run out of memory.
You can then use Carbons createFromFormat() method to specify how to parse the current date format and update the record.
Accounts::orderBy('id')->chunk(100, function ($accounts) {
foreach ($accounts as $account) {
$account->update([
'expiration_date' => Carbon::createFromFormat('d M Y', $account->expires_in)
]);
}
});
Found this post about converting string to date
Update `accounts` set `expiration_date` = STR_TO_DATE(expires_in, '%d %M %Y')

How to convert dates within an array to a specific format

I have an array of dates, where the dates have different formats. I would like to convert them all to the same format, however what I've tried has caused me some problems.
I get the dates from a SQL query:
table_birth_dates = self.class.connection("SELECT birth_date FROM #{temp_table_name}").values
which gives me an array of dates:
[
[0] "10/3/80",
[1] "10/3/81",
[2] "10/3/01",
[3] "33/33/1970",
]
I want to get the year as a full year like above.
I tried:
table_birth_dates.first.to_time
and got:
ArgumentError: argument out of range
I also tried:
Date.strptime(table_birth_dates)
and got:
no implicit conversion of Array into String
Does anyone have any ideas?
As the others already said: Don't store arbitrary strings as date! Use your database and store dates as date or datetime. See documentation of your database. (See comment from #the-tin-man.)
That said you can try the following with your current date:
table.map! { |date|
date_hash = Date._strptime(date, '%m/%d/%Y') # {:mon=>10, :mday=>3, :year=>70}
if date_hash.nil?
'invalid'
else
date_hash[:year] = date_hash[:year] + 1900 if date_hash[:year] < 1000
Date.new(date_hash[:year], date_hash[:mon], date_hash[:mday])
end
}
This gives you an array with actual dates like so:
[
1980-10-03
1981-10-03
1901-10-03
invalid
]
Of course you should do something about this invalid but it serves your main purpose.
If all you dates is on the the same format as the first 3 dates you can use this con change the format of the dates:
dates.map! do |date|
Date.strptime(date, '%d/%m/%y').strftime('%d/%m/%Y')
end
If you have dates on different formats you could list the formats you have and try to parse each of them and see if you get a valid result, however dates like 33/33/1970 is not a valid date at all.
Parsing dates isn't as straightforward as people assume when they first start working with them, because dates are represented differently around the world.
'10/3/80'
would represent "October 3, 1980" in a U.S. formatted date, but would be "March 10, 1980" in the rest of the world. And, the software has no idea which it is unless you tell it which to use. And, if your data comes from around the world you can't tell unless you know what locale the data was generated in or unless they explicitly tell you what format it's in.
require 'date'
Date.strptime('10/3/80', '%m/%d/%y') # => #<Date: 1980-10-03 ((2444516j,0s,0n),+0s,2299161j)>
Date.strptime('10/3/80', '%d/%m/%y') # => #<Date: 1980-03-10 ((2444309j,0s,0n),+0s,2299161j)>
From DB, bring date in integer format and convert back to any specific format.
Are you storing date in DB as string and trying to convert them for unique format to display? If so, you can correct while storing the value (or) add a column in DB which gets updated whenever your date column gets inserted/updated and retrieve from new column.

Resources