Retrieving date format with am/pm in codeigniter - codeigniter

I have converted date to my local time as below:
$this->date_string = "%Y/%m/%d %h:%i:%s";
$timestamp = now();
$timezone = 'UP45';
$daylight_saving = TRUE;
$time = gmt_to_local($timestamp, $timezone, $daylight_saving);
$this->updated_date = mdate($this->date_string,$time);
And I'm storing this field in to database.
Now at retrieval time I want format like this:
"11-04-2011 4:50:00 PM"
I have used this code:
$timestamp = strtotime($rs->updated_date);
$date1 = "%d-%m-%Y %h:%i:%s %a";
$updat1 = date($date1,$timestamp);
But this will give me only
"11-04-2011 4:50:00 AM"
But I have stored it like it was PM.

Might get voted down, but will have a go at it.
Is it because the MySQL stores it in 24 hour format? (assuming you are using the datetime field type)
Maybe this will help
Converting mysql TIME from 24 HR to AM/PM format
sorry if it doesn't.

Related

Java 8 - SQL Timestamp to Instant with properly formatted time

I've read through the available q and a on SO, but nothing I have found answers my question of how to format my time in 12hour format.
Following is my code that runs a query on a MySQL database and returns results, checking to see if an appointment is within 15 minutes of login so an alert can pop.
public void apptCheck(int userId) throws SQLException {
// this method checks for an appointment occurring within 15 minutes of login
Statement apptStatement = DBQuery.getStatement();
String apptQuery = "Select apt.start, cs.customerName from DBName.appointment apt "
+ "JOIN DBName.customer cs ON cs.customerId = apt.customerId WHERE "
+ "userId = " + userId + " AND start >= NOW() AND start < NOW() + interval 16 minute";
apptStatement.execute(apptQuery);
ResultSet apptRs = apptStatement.getResultSet();
while(apptRs.next()) {
Timestamp apptTime = apptRs.getTimestamp("start");
ResourceBundle languageRB = ResourceBundle.getBundle("wgucms/RB", Locale.getDefault());
Alert apptCheck = new Alert(AlertType.INFORMATION);
apptCheck.setHeaderText(null);
apptCheck.setContentText(languageRB.getString("apptSoon") + " " + apptTime.toInstant().atZone(ZoneId.systemDefault()));
apptCheck.showAndWait();
}
My result is:
I want the time to display 3:00, not the 19:00 - 06:00. How can I make that happen?
ZonedDateTime zonedDateTime=ZonedDateTime.of(apptTime.toLocalDateTime(),ZoneId.systemDefault());
You can use ZonedDateTime and format the time as you want.
docs.oracle.com/javase/8/docs/api/java/time/ZonedDateTime.html ZonedDateTime has a lot of features you can see all here and you can get the hour, minute, day etc.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("hh:mm:ss");
String formattedString = zonedDateTime.format(formatter);
if you only want time in 12hour format you can use this
I found the solution which will perform the UTC to local time conversion and then format the time so that the resulting alert is in 12 hour time format without the date or time zone info. Here is the full code:
while(apptRs.next()) {
Timestamp apptTime = apptRs.getTimestamp("start");
// perform time conversion from UTC to User Local Time
ZoneId zidApptTime = ZoneId.systemDefault();
ZonedDateTime newZDTApptTime = apptTime.toLocalDateTime().atZone(ZoneId.of("UTC"));
ZonedDateTime convertedApptTime = newZDTApptTime.withZoneSameInstant(zidApptTime);
ResourceBundle languageRB = ResourceBundle.getBundle("wgucms/RB", Locale.getDefault());
Alert apptCheck = new Alert(AlertType.INFORMATION);
apptCheck.setHeaderText(null);
// set the Alert text and format in 12 hour format
apptCheck.setContentText(languageRB.getString("apptSoon") +
convertedApptTime.toInstant().atZone(ZoneId.systemDefault())
.format(DateTimeFormatter.ofPattern("h:mm a")) + ".");
apptCheck.showAndWait();
}

How to split date and time from a string like 8/29/2011 1:00 PM in laravel

in my blade there is a DateTime picker which selects in mm/dd/yyyy hh:mm AM/PM format. and i need to extract this to date = 8/29/2011 and time = 13:00 .
how can I do that?
Do as below.
$stringdate = "8/29/2011 1:00 PM";
$timestemp = strtotime($stringdate);
$date = date('Y-m-d', $timestemp);
$time = date('H:i:s',$timestemp);
echo $date;
echo $time;
check example
Edit:- as you want this format YYYY-MM-DD hh:mm
$datetime = date('Y-m-d H:i', strtotime("8/29/2011 1:00 PM"));
echo $datetime; //output "2011-08-29 13:00";
Try this way.
#php
$input = '2017-06-27 12:58:20';
$format1 = 'Y-m-d';
$format2 = 'H:i:s';
$date = Carbon\Carbon::parse($input)->format($format1);
$time = Carbon\Carbon::parse($input)->format($format2);
#endphp
It is simple just try it
$date="8/29/2011 1:00 PM"; // date that get from view (blade page)
$createTimestamp = new DateTime($date); // create timestamp object from string
$date = $createTimestamp->format('m/d/Y'); // get date
$time = $createTimestamp->format('H:i:s A'); // get time with AM/PM format
return "date: ".$date." time: ".$time; // return your result
Try this way
Use Carbon;
$dateAndTime=Carbon::parse('8/29/2011 1:00 PM');
$date=$dateAndTime->format('d-m-Y');// 29-8-2011
$time=$dateAndTime->format('H:i:s');// 1:00
$time=$dateAndTime->format('H:i:s A');// 1:00 AM/PM
Refer this link to understand more about Carbon.

UTC to local method in DateTimeZone of Joda-Time to Java 8

We are changing Joda-Time API's to Java 8 time API's. In Joda-Time I have used:
DateTimeZone.convertLocalToUTC(this.getMillis(), true);
DateTimeZone.convertUTCToLocal(long millis);
Can any one tell me equivalent methods in Java 8?
Edited
convertLocalToUTC
DateTimeZone dateTimeZone = DateTimeZone.getDefault();
DateTime jodadatetime = new DateTime();
long utcTime = dateTimeZone.convertLocalToUTC(jodadatetime .getMillis(), true);
System.out.println(jodadatetime);
DateTimeZone dateTimeZone1 = DateTimeZone.UTC;
System.out.println(new DateTime(utcTime, dateTimeZone1));
Output
2017-08-09T17:27:57.508+05:30
2017-08-09T06:27:57.508Z
ConvertUtcToLocal
long utctolocal = dateTimeZone.convertUTCToLocal(jodadatetime.getMillis());
System.out.println("utc to local : " + new DateTime(utctolocal, dateTimeZone1));
Output
2017-08-09T17:27:57.508Z
So, your original date is 2017-08-09T17:27:57.508+05:30, then you want 2 things:
convertLocalToUTC: get 2017-08-09T06:27:57.508Z. This is a little bit tricky:
The original date is 2017-08-09T17:27:57.508+05:30, which is equivalent in UTC to 2017-08-09T11:57:57.508Z. What this method does is to convert this to the same local date and time but at the Calcutta timezone, and then you're printing it in UTC. In short:
original date is 2017-08-09T17:27:57.508+05:30
in UTC, that's the same as 2017-08-09T11:57:57.508Z
convertLocalToUTC converts this to 2017-08-09T11:57:57.508+05:30 (same date and time, but in Calcutta timezone)
and that's the same as 2017-08-09T06:27:57.508Z
To do this in Java 8, you can do:
ZoneId zone = ZoneId.of("Asia/Calcutta");
// original date 2017-08-09T17:27:57.508+05:30
Instant i = OffsetDateTime.parse("2017-08-09T17:27:57.508+05:30")
// convert to UTC (2017-08-09T11:57:57.508Z)
.atZoneSameInstant(ZoneOffset.UTC)
// convert to same local time in Calcutta
.withZoneSameLocal(zone)
// back to UTC
.toInstant();
System.out.println(i.toEpochMilli() + "=" + i);
Output:
1502260077508=2017-08-09T06:27:57.508Z
convertUTCToLocal: get 2017-08-09T17:27:57.508Z - the same date (2017-08-09) and time (17:27:57.508) but in UTC.
It's similar:
ZoneId zone = ZoneId.of("Asia/Calcutta");
// original date 2017-08-09T17:27:57.508+05:30
ZonedDateTime z = OffsetDateTime.parse("2017-08-09T17:27:57.508+05:30")
// convert to a ZonedDateTime in Calcutta (2017-08-09T17:27:57.508+05:30[Asia/Calcutta])
.atZoneSameInstant(zone)
// convert to same local time in UTC
.withZoneSameLocal(ZoneOffset.UTC);
System.out.println(z.toInstant().toEpochMilli() + "=" + z);
Output:
1502299677508=2017-08-09T17:27:57.508Z
You can also get the dates from the millis value.
For case 1:
// millis for original joda date: jodadatetime.getMillis() (1502279877508 = 2017-08-09T17:27:57.508+05:30)
long millisFromJoda = 1502279877508L;
Instant instant = Instant.ofEpochMilli(millisFromJoda)
// convert to UTC (2017-08-09T11:57:57.508Z)
.atZone(ZoneOffset.UTC)
// convert to same local time in Calcutta
.withZoneSameLocal(zone)
// back to UTC
.toInstant();
System.out.println(instant.toEpochMilli() + "=" + instant);
Output:
1502260077508=2017-08-09T06:27:57.508Z
You can convert the Instant to another types if you want:
// convert to ZonedDateTime in UTC
ZonedDateTime zd = instant.atZone(ZoneOffset.UTC);
// convert to OffsetDateTime in UTC
OffsetDateTime odt = instant.atOffset(ZoneOffset.UTC);
Both will be 2017-08-09T06:27:57.508Z.
And for case 2:
ZonedDateTime zdt = Instant.ofEpochMilli(millisFromJoda)
// convert to a ZonedDateTime in Calcutta (2017-08-09T17:27:57.508+05:30[Asia/Calcutta])
.atZone(zone)
// convert to same local time in UTC
.withZoneSameLocal(ZoneOffset.UTC);
System.out.println(zdt.toInstant().toEpochMilli() + "=" + zdt);
Output:
1502299677508=2017-08-09T17:27:57.508Z
Here is some code snippet that may help you get started:
LocalDateTime yourLocalTime = ...
long utc = yourLocalTime.toInstant(ZoneOffset.UTC).toEpochMilli();
or as you used strict = true the following:
long utc = ZonedDateTime.ofStrict(yourLocalTime, ZoneOffset.UTC, ZoneId.of("Z")).toInstant().toEpochMilli();
Converting back is similar:
LocalDateTime yourUtcTime = ...
long localTimeInMillis = yourUtcTime.toInstant(OffsetDateTime.now().getOffset() /* or: yourLocalTime.getOffset() */).toEpochMilli();
If you don't need the millis, but want to work with the DateTime-classes instead, you may want to use ZonedDateTime instead?
Creating a LocalDateTime from millis could be done as follows:
LocalDateTime yourLocalDateTime = Instant.ofEpochMilli(millisAsLong).atZone(/* your desired zone here */).toLocalDateTime();
where zone id could be ZoneId.of("Z"), ZoneId.systemDefault(), etc.

How to use timezones in Laravel?

The user creates date in format like as: 12/23/2016 22:10
After this data should be sent convert to another timezone, for example GMT + 2:
12/23/2016 00:10
I can assume the date that I create should be saved in GTM 0, only after I can change timezone.
How can I use this mechanism in Laravel?
You can use Carbon to change the the timezone of a date as:
$date = Carbon\Carbon::parse('12/23/2016 22:10', 'GMT');
And to add +2 you can do as:
$date->addHours(2)
You can change the timezone for your application in: /config/app.php,
The default timezone is UTC. You can find all supported timezones here: http://php.net/manual/en/timezones.php
Mostly I'm agree with Amit Gupa answer, but the best way to manage timezone conversion isn't by adding hours, but by converting it on Carbon:
$yourdate->timezone('somecountrytimezone')
This way you won't have to worry about different time management between countries (Like daylight saving time) and just manage to get your works done.
Please refer do the documentation : http://carbon.nesbot.com/docs/#api-settersfluent
We can use parse and createFromFormat methods of Carbon to set our datetime as a certain timezone then use setTimezone to convert it to another timezone.
$date = "2022-08-05 12:00:00"; //set datetime for checking
$now = Carbon::now()->timezone('Europe/London')->format('Y-m-d H:i:s');
$createFrom = Carbon::createFromFormat('Y-m-d H:i:s', $date, 'Asia/Hong_Kong')->format('Y-m-d H:i:s');
$parse = Carbon::parse($date,'Asia/Hong_Kong')->setTimezone('Europe/London')->format('Y-m-d H:i:s');
$converted = Carbon::parse($date,'Asia/Hong_Kong')->timezone('Europe/London')->format('Y-m-d H:i:s');
outputs: when dd($now,$createFrom,$parse,$converted);
^ "2022-08-05 08:33:48"
^ "2022-08-05 12:00:00"
^ "2022-08-05 05:00:00"
^ "2022-08-05 05:00:00"
that's not related to laravel , it's just a php , so you can simply get the time-zone offset (exp GMT+3) then do like this :
$timeZoneOffset ---> for GMT+3 you put (3)
function getNewDateByTimeZone($date, $timeZoneOffset)
{
/* if the client Time zone is GMT */
if (!$timeZoneOffset || $timeZoneOffset == 0) {
$timeZoneOffset = "-0";
}
$op = $timeZoneOffset[0];
$timeZoneOffset = preg_replace('/[^0-9.]+/', '', $timeZoneOffset) * 60;
$userDate = date($date, time());
$timeStamp = strtotime($userDate);
$offsetTime = $op == '-' ? $timeStamp + $timeZoneOffset : $timeStamp - $timeZoneOffset;
return date("Y-m-d H:i", $offsetTime);
}
so like that you will save the date in GMT-0

Codeigniter time showing as AM not PM

I am using the codeigniter time helper to echo the TIMESTAMP (CURRENT_TIMESTAMP) row of my mysql database.
The timestamp in my database in raw format is: 2011-11-15 14:40:45
When I echo the time in my view using the helper i get the following: 15/11/2011 02:40
My time now appears to be in AM. Why???
This is the code I use to echo the time:
$the_date = mdate('%d/%m/%Y %h:%i', strtotime($row->date))
echo $the_date
You need to change the format of your data when returning it from the database. Chage the lowercase h (%h) to a capital H (%H) to return 24-hour format rather than the 12 hour you're currently getting.
You're code should look like the below:
$the_date = mdate('%d/%m/%Y %H:%i', strtotime($row->date))

Resources