How to add Date and Time to get DateTime in Laravel? - laravel

I have two columns in my DB: date and time. I want to combine them into DateTime so that I can use diff() to get a difference between the current time and the combined DateTime.

$query = DB::query("select concat(date," ",time) as datetime from TABLENAME"); using this row query you can concat the date and time DB values; and it will works like datetime value.

You can use mutators for this:
// assuming your date field is in format Y-m-d and time H:i:s
// and you want the property named someTimestamp
public function getSomeTimestampAttribute()
{
// use Carbon\Carbon for the class
return new Carbon($this->attributes['date'] . ' ' . $this->attributes['time']);
}
public function setSomeTimestampAttribute($dateTime)
{
// parse param to get string 'Y-m-d H:i:s'
$dateTime = $this->fromDateTime($dateTime);
$date = substr($dateTime, 0, 10); // Y-m-d
$time = substr($dateTime, 11); // H:i:s
$this->attributes['date'] = $date;
$this->attributes['time'] = $time;
}
Then you can do this:
// get
$model->someTimestamp; // Carbon instance depending on date & time db fields
$model->someTimestamp->diff(Carbon::now());
// set - all methods do the same
$model->someTimestamp = new Carbon('2014-08-31 11:55:00');
$model->someTimestamp = new DateTime('2014-08-31 11:55:00');
$model->someTimestamp = '2014-08-31 11:55:00';
// then this is true
$model->date; // 2014-08-31
$model->time; // 11:55:00
// so you can now call ->save() on the model and values in db will be correct

Concatenating the two variables storing wasn't enough, it needed more. I am using Laravel, so in my case this did the trick:
$datetime = $date.' '.$time;
$datetime = new DateTime($datetime);
All I needed was a DateTime object, and this is how I got it. So after this I can easily get the difference between two DateTime objects.
$currentDateTime = new DateTime(); //Returns current time & date in a DateTime object
$difference = $currentDateTime->diff($datetime);
$difference has all that I wanted.

Related

I can't get createdAt value form Parse(Back4App) by using PHP

Despite I use $object->getCreatedAt() function I cant fetch the createdAt column's values. Need help. Thanks in advance for all.
$tableFetch = new Database(); // This is my custom class structure
$subscriptions = $tableFetch->tableFetch("Subscribe");
for ($i = 0; $i < count($subscriptions); $i++) {
$object = $subscriptions[$i];
$createdAt = $object->getCreatedAt();
}
Edit: I can get the information of array but cant slice it with keys.
I found the answer.
After creating DateTime Object need to specify format as below.
$createdAt->format('Y-m-d H:i:s');

JSON selector `field->key` causes syntax error in laravel 5.4

I have dates like this :- $startdate= 10/23/2017 and $enddate =10/28/2017 ..need to compare with database table key name availablityschedule which is in serialize form like a:2:{s:10:"start_date";s:10:"2017-07-24";s:8:"end_date";s:10‌​:"2017-07-31";}
If all your dates are posterior to the 1st of January of 1970, you could use something like:
$startDate= date("Y-m-d");
$endDate = $JSONObject->endDate
$startDate = strtotime($startDate);
$endDate = strtotime($endDate);
if ($endDate < $startDate) { /* do Something */ }
If you are using PHP > 5.0 you can use the class DateTime
$today_dt = new DateTime($startDate);
$expire_dt = new DateTime($endDate);
if ($expire_dt < $today_dt) { /* Do something */ }
Asuming of course you would like to do this in the backend side with php.

How to create logic hook in SuiteCRM Leads to calculate and display Days Since Last Activity for a given record

This would be displayed in a new field Days Since Last Activity and based on Today minus Date Modified.
You can do something like this on whatever hook u want
<?php
if (!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
class logic_hooks_class
{
function after_retrieve_method($bean, $event, $arguments)
{
$date_modified = $bean->date_modified;
$datetime1 = new DateTime();
$datetime2 = new DateTime($date_modified);
$interval = $datetime1->diff($datetime2);
$elapsed = $interval->format('%a');
$bean->days_since_last_activity_c = $elapsed;
}
}
?>

Laravel excel import, date column in excel cell returns as floating value. How to solve this?

By using Maatwebsite/Laravel-Excel to import excel sheet, here I faced an issue date time column of the excel sheet returns float value. How to solve this?
Example : Consider Cell value "08-04-2016 13:08:29" and returns as "42104.487060185" when import.
This only happend when use chunk. This issue could be solved by:
$UNIX_DATE = ($row->DOB - 25569) * 86400;
$date_column = gmdate("d-m-Y H:i:s", $UNIX_DATE);
Known bug, see https://github.com/Maatwebsite/Laravel-Excel/issues/404 for details.
But basically, when using chunk() to read the cells in, it fails to convert Excel's datetime format from a float into a Carbon date object.
There is currently no fix, You can work around this by calling config before the call to load:
config(['excel.import.dates.columns' => [
'deleted_at',
'updated_at'
]]);
Excel::filter('chunk')->load($file)->chunk(100 function($rows) { ... });
If you're not using the chunk filter, then see http://www.maatwebsite.nl/laravel-excel/docs/import#dates on how to explicty set formats on cells (setDateColumns()), but those should be converting automatically unless you change the defaults.
Change the format your import file to .csv and format the date column to your required date format (dd-mm-yyyy)
That "floating number" is an excel timestamp, that way it stores the date and time data internally.
for example:
123213.0: it's just a date
213233.1233: is a date and time
0.1233: it's one hour
To solve this you must convert that floating point number to a date.
if your need involves resolving datetime fields dynamically, I have written a method that is responsible for automatically detecting if the value is a datetime dynamically (regardless of whether or not you know if there will be a datetime in that column) or I have tried various data types and it works fine
/**
* #param Cell $cell
* #param $value
*
* #return boolean;
*/
public function bindValue(Cell $cell, $value)
{
$formatedCellValue = $this->formatDateTimeCell($value, $datetime_output_format = "d-m-Y H:i:s", $date_output_format = "d-m-Y", $time_output_format = "H:i:s" );
if($formatedCellValue != false){
$cell->setValueExplicit($formatedCellValue, DataType::TYPE_STRING);
return true;
}
// else return default behavior
return parent::bindValue($cell, $value);
}
/**
*
* Convert excel-timestamp to Php-timestamp and again to excel-timestamp to compare both compare
* By Leonardo J. Jauregui ( #Nanod10 | siskit dot com )
*
* #param $value (cell value)
* #param String $datetime_output_format
* #param String $date_output_format
* #param String $time_output_format
*
* #return $formatedCellValue
*/
private function formatDateTimeCell( $value, $datetime_output_format = "Y-m-d H:i:s", $date_output_format = "Y-m-d", $time_output_format = "H:i:s" )
{
// is only time flag
$is_only_time = false;
// Divide Excel-timestamp to know if is Only Date, Only Time or both of them
$excel_datetime_exploded = explode(".", $value);
// if has dot, maybe date has time or is only time
if(strstr($value,".")){
// Excel-timestamp to Php-DateTimeObject
$dateTimeObject = \PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($value);
// if Excel-timestamp > 0 then has Date and Time
if(intval($excel_datetime_exploded[0]) > 0){
// Date and Time
$output_format = $datetime_output_format;
$is_only_time = false;
}else{
// Only time
$output_format = $time_output_format;
$is_only_time = true;
}
}else{
// Only Date
// Excel-timestamp to Php-DateTimeObject
$dateTimeObject = \PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($value);
$output_format = $date_output_format;
$is_only_time = false;
}
// Php-DateTimeObject to Php-timestamp
$phpTimestamp = $dateTimeObject->getTimestamp();
// Php-timestamp to Excel-timestamp
$excelTimestamp = \PhpOffice\PhpSpreadsheet\Shared\Date::PHPToExcel( $phpTimestamp );
// if is only Time
if($is_only_time){
// 01-01-1970 = 25569
// Substract to match PhpToExcel conversion
$excelTimestamp = $excelTimestamp - 25569;
}
/*
// uncoment to debug manualy and see if working
$debug_arr = [
"value"=>$value,
"value_float"=>floatval($value),
"dateTimeObject"=>$dateTimeObject,
"phpTimestamp"=>$phpTimestamp,
"excelTimestamp"=>$excelTimestamp,
"default_date_format"=>$dateTimeObject->format('Y-m-d H:i:s'),
"custom_date_format"=>$dateTimeObject->format($output_format)
];
if($cell->getColumn()=="Q"){
if($cell->getRow()=="2"){
if(floatval($value)===$excelTimestamp){
dd($debug_arr);
}
}
}
*/
// if the values match
if( floatval($value) === $excelTimestamp ){
// is a fucking date! ;)
$formatedCellValue = $dateTimeObject->format($output_format);
return $formatedCellValue;
}else{
// return normal value
return false;
}
}

input date using jdbc to hsqldb

How do i get all the rows having endDate greater than current date? do i have to use setString() or setDate()? they are both not working!!!
What is the correct way to do it?
ResultSet is empty but database contains data for the given sql statement
public ArrayList<AddBean> listPendingTasks() {
java.util.Date date = new java.util.Date();
String modifiedDate= new SimpleDateFormat("yyyy-MM-dd").format(date);
Connection con = JDBCHelper.getConnection();
PreparedStatement ps_sel = null;
ArrayList<AddBean> c = new ArrayList<AddBean>();
ResultSet rs = null;
try {
ps_sel = con.prepareStatement("select * from tasks where enddate > ? order by enddate");
ps_sel.setString(2, modifiedDate);
ps_sel.execute();
rs = ps_sel.getResultSet();
while(rs.next())
{
AddBean ab = new AddBean();
ab.setTname(rs.getString(2));
ab.setCategory(rs.getString(3));
ab.setStartdate(rs.getString(4));
ab.setEnddate(rs.getString(5));
ab.setDescription(rs.getString(6));
ab.setPriority(rs.getString(7));
c.add(ab);
}
return c;
} catch (SQLException e) {
e.printStackTrace();
return null;
}
try this
If your table has a column of type DATE:
Query : SELECT * FROM [values] v WHERE date >= '2013-06-03';
Then use this method java.sql.Date.valueOf(java.lang.String)
ps.setDate(2, java.sql.Date.valueOf("2015-09-13"));
Updated with Date and Time Types:
The DATE type is used for values with a date part but no time part. MySQL retrieves and displays DATE values in 'YYYY-MM-DD' format. The supported range is '1000-01-01' to '9999-12-31'. MySQL retrieves and displays TIME values in 'HH:MM:SS' format. TIME values may range from '-838:59:59' to '838:59:59'.
String QUERY = "UPDATE TABLE_NAME SET dateValue=?, timeValue=?, timeStampText=? WHERE rowIdentify=?";
PreparedStatement pstmt = con.prepareStatement( QUERY );
pstmt.setDate(1, java.sql.Date.valueOf( localDate )); // DATE Type
pstmt.setTime(2, java.sql.Time.valueOf( localTime )); // TIME Type
pstmt.setString(3, localDateTime ); // TEXT Type
pstmt.setString(4, conditionValue );
Sample code to get the above Date fields value. getDateFromEpochTime()
long startTime=System.currentTimeMillis();
String str = getDateFromEpochTime(startTime);
CharSequence charSequence = str.subSequence(0, str.length());
String pattern = "yyyy-MM-dd HH:mm:ss";
DateTimeFormatter dateTimeFormatter = java.time.format.DateTimeFormatter.ofPattern( pattern );
LocalDate localDate = java.time.LocalDate.parse( charSequence, dateTimeFormatter );
LocalTime localTime = java.time.LocalTime.parse( charSequence, dateTimeFormatter );
LocalDateTime localDateTime = LocalDateTime.parse( charSequence, dateTimeFormatter);
Java SQL driver doesnot support java.sql.Timestamp for DATETIME or TIMESTAMP type of Table column. Try to use PreparedStatement when query contains Date and Time Types types.
learn the date format of the db. hsql db supports 'yyyy-mm-dd'. If you are using prepared statements, then you can input date as a String or a date. that is not going to make a difference. I recommend using string. Using date is a little complicated for beginners because its not util date. Its sql date. Date formats can sometime be troublesome.

Resources