I have a string that contains date and time. Format of my string is yyyymmddtime.
For example. 20171125123000209. this is my complete string in which first comes the month, then month and then day after that time. How can i retrieve date from it by converting to readable date format. I tried with php's date function. But the output was not as expected. Please help.
Try this
<?php
$str_date= "20171125123000209";
$exiting_date_format='Ymd';
//first 8 characters from given date string in second parameter below
$date = DateTime::createFromFormat($exiting_date_format, substr($str_date,0,8));
echo $date->format('Y-m-d');//specify desired date format
?>
Output :
2017-11-25
DateTime::createFromFormat - Parses a time string according to a specified format
You can use date() function of php
<?php
$full_date= "20171125123000209";
echo date('dS F h:i:s A', $full_date);
//Output = 31st May 12:30:09 AM
?>
Or,
To get date from timestamp like now,
$timestamp= time(); //Or your timestamp here
$date = date('d-m-Y', $timestamp); //Inside first parameter, give your date format
echo $date; //17-12-2017
Or,
To get anything from string you can also use substr() function of php.
<?php
$full_date= "20171125123000209";
$year = substr($full_date, 0, 4);
$month = substr($full_date, 4, 2);
$date = substr($full_date, 6, 2);
echo 'Year = '.$year.' ';
echo 'Month = '.$month.' ';
echo 'Date = '. $date.' ';
?>
Output:
Year = 2017 Month = 11 Date = 25
Test in jdoodle
About substr() function in php
It's not necessary to manipulate the string at all. PHP's DateTime class supports parsing a string containing miliseconds natively, using the u format modifier:
$str = '20171125123000209';
$date = DateTime::createFromFormat('YmdHisu', $str);
Using your new $date object, you can convert to whatever format you're looking for, e.g.
echo $date->format("F j Y, g:i a");
// November 25 2017, 12:30 pm
See https://eval.in/920636
$your_strtotime_val = ""; //20171125123000209
$convert_to_date = date("m-d-Y h:i:s",$your_strtotime); // [m-d-Y h:i:s] this depending on how you convert date in first time so be careful
Related
I am dealing with a problem of time conversion from 12 hr format to 24 hour format.
Is there any single function in php to replace the first two characters of a string?
str_replace can be used only when I know the substring content to be replaced.
$str_to_replace = '12';
$input_str = 'ab345678';
$output_str = $str_to_replace . substr($input_str, 2);
echo $output_str;
"12345678"
If the date is always given in a specific format you could try to convert it to a DateTime object and format the output.
$dateString = '15-Feb-2009 2:24 PM';
$date = DateTime::createFromFormat('j-M-Y g:i A', $dateString);
echo $date->format('Y-m-d G:i'); // will show "2009-02-15 14:24"
In general you should try in avoid holding a date in a string. Convert it to a DateTime -- this makes it also easier for you to manipulate the object (e.g. move date +1 day)
I have a string: 30/06/18 (30th June 2018)
I am converting to a date:
$calcFieldDate = date_create_from_format('d/m/y', '30/06/18')->format('d-m-Y');
echo $calcFieldDate;
Result: 18-06-2018
Now I want to add 20 days to the date:
$expiryDate = date("d-m-Y", strtotime("+20 days", $calcFieldDate));
echo $expiryDate;
Expected Result: 08-07-2018
Actual Result: 31-01-1970
I am obviously creating a date format which is then subsequently being treated as a string...
Every time I try a conversion, I just hit another road block - is there anyway to create a date that is then treated like a date?
$calcFieldDate = date_create_from_format('d/m/y', '30/06/18')->format('d-m-Y');
echo $calcFieldDate;
Result:30-06-2018
$expiryDate = date("d-m-Y", strtotime("+20 days", strtotime($calcFieldDate)));
echo $expiryDate;
Result:20-07-2018
Strtotime() The second parameter is the timestamp
You actually don't need to revert using strtotime and date functions, you can actually use DateTime to simply add dates into it:
$calcFieldDate = date_create_from_format('d/m/y', '30/06/18');
echo $calcFieldDate->format('d-m-Y'); // get inputted date
$expiryDate = clone $calcFieldDate; // clone the original date object
$expiryDate->modify('+20 days'); // adjust the cloned date
echo $expiryDate->format('d-m-Y'); // show the adjusted date
This will sort your problem.
$str="30/06/18 (30th June 2018)";
$arr_temp=explode(" ",$str);
$str_date=str_replace("/","-",$arr_temp[0]);
$dt = DateTime::createFromFormat('d-m-y',$str_date);
$date=$dt->format('d-m-Y');
$new_date=date('d-m-Y',strtotime("+20 days",strtotime($date)));
echo $new_date;
If I have this date: "16/2/2014 3:41:01 PM" and would like to change it to the format: "2014-02-16 15:41:01".
How can I do it with PHP?
I tried this:
$date = "16/2/2014 3:41:01 PM"
$newDate = date("Y-m-d H:i:s", strtotime($date));
but it keeps returning "1970-01-01 00:00:00".
The current format of your $date string is invalid in terms of how PHP reads and parses dates - See these two URLs for specifics:
http://php.net/manual/en/function.strtotime.php
http://php.net/manual/en/datetime.formats.php
Essentially, when using slashes (/) as date separators, PHP assumes you're entering MM/DD/YYYY. If at all possible, I'd see about updating whatever input created that date string to save it in MM/DD/YYYY format - That would probably be the best solution.
However, if that's not an option, based on what you've given, one method would be to swap the 16 and 2 to go from a DMY to an MDY format. Here's an example on how to do that using explode() and string concatenation:
<?php
// The original string you provided, with a date in `DD/MM/YYYY` format
$dateString = "16/2/2014 3:41:01 PM";
// The explode function will let us break the string into 3 parts, separated by the forward slashes. Using your example, these gives us an array containing the following:
// 0 => '16'
// 1 => '2'
// 2 => '2014 3:41:01 PM'
$stringPieces = explode('/', $dateString, 3);
// Piece the above array back together, switching the places of entries 0 and 1 to create a date in the format `MM/DD/YYYY`. This results in:
// 2/16/2014 3:41:01 PM"
$newDateString = $stringPieces[1] . '/' . $stringPieces[0] . '/' . $stringPieces[2];
// Use the reformatted date string in the date() function:
$newDate = date("Y-m-d H:i:s", strtotime($newDateString));
var_dump($newDate);
The output of var_dump() in my testing was string(19) "2014-02-16 15:41:01"
Use this function
Date and Time format
1: This function will help you
function date_his($date = '')
{
if ($date == '') {
return $date = date("Y-m-d H:i:s");
} else {
$date = date("Y-m-d H:i:s", strtotime($date));
}
return $date;
}
2: While store in to database call this function like this
$date = date_his();
it will consider current date and current time
3: If you want to store the date from date field call like this
$date = date_his($_POST['field_name']);
Bonus
It converts any date and time format into YYYY-mm-dd HH:mm:ss
How do I convert 2014-10-10 04:13:24 to 2014-10-10T04:13:24+00:00 in php or mysql
The above mentioned date is for xml format in sitemaps
For reference check Q: How do I compute lastmod date? (Sitemaps.org FAQ)
code which i have tried:
echo "GIVEN DATE ".$timestamp = "2014-10-10 04:13:24";
echo "<br>";
$year = date('Y',strtotime($timestamp)).";
$month = date('m',strtotime($timestamp)).";
$day = date('d',strtotime($timestamp))."";
echo '<br>';
$hour = date('H',strtotime($timestamp))."";
$minutes = date('i',strtotime($timestamp))."";
$seconds = date('s',strtotime($timestamp))."<br>";
$gmktime= gmmktime($hour,$minutes,$seconds,$month,$day,$year)."<br>";
echo "output date".$isodate = date('c', $gmktime);
is the above out put conversion correct?
**OUTPUT**
GIVEN DATE : 2014-10-10 04:13:24
output date : 2014-10-10T06:13:24+02:00
Your output is correct in the light of the Sitemaps.org spec. "2014-10-10T06:13:24+02:00" is the same date/time as "2014-10-10T04:13:24+00:00".
Learn more about the W3C Datetime encoding which is used by Sitemaps.org.
Also, don't solve this with date functions, solve this with string function / operations: You change a single byte inside a string at a fixed position and then you append a string:
$timestamp = "2014-10-10 04:13:24";
$timestamp[10] = "T";
$timestamp .= "+00:00";
echo $timestamp, "\n"; // 2014-10-10T04:13:24+00:00
Or if you like to save some bytes in your file use "Z" instead of "+00:00" to denote the timezone:
$timestamp = "2014-10-10 04:13:24";
$timestamp[10] = "T";
$timestamp .= "Z";
echo $timestamp, "\n"; // 2014-10-10T04:13:24Z
PHP 5:
<?php
// Set the default timezone
date_default_timezone_set('UTC');
// Get Unix timestamp for a date
// Reference: mktime(hour, minute, second, month, day, year)
$time = mktime(04, 13, 24, 10, 10, 2014);
// Alternatively (must be a valid English date format)
$time = strtotime('2014-10-10 04:13:24');
// ISO 8601 date (added in PHP 5)
$isodate = date('c', $time);
echo $isodate; // 2014-10-10T04:13:24+00:00
// RFC 2822 formatted date
$rfcdate = date('r', $time);
echo $rfcdate; // Fri, 10 Oct 2014 04:13:24 +0000
?>
References:
date() / gmdate()
mktime() / gmmktime()
strtotime() : Supported Date and Time Formats
date_default_timezone_set() : List of Supported Timezones
ISO 8601
RFC 2822
In PHP
In PHP you use strptime() to parse the time and turn it into a structured array. Then pass the results of that into the mktime() function to get a UNIX timestamp.
In MySQL
Use UNIX_TIMESTAMP
SELECT UNIX_TIMESTAMP(datetime_column) FROM table;
I have a date/time string like this: 180510_112440 in this format ddmmyy_hhmmss
I need a snippet for having a string formatted like this way: 2010-05-18 11:24:40
Thanks for help.
another possible answer is the common use of strptime to parse your date and the mktime function:
<?php
$orig_date = "180510_112440";
// Parse our date in order to retrieve in an array date's day, month, etc.
$parsed_date = strptime($orig_date, "%d%m%y_%H%M%S");
// Make a unix timestamp of this parsed date:
$nice_date = mktime($parsed_date['tm_hour'],
$parsed_date['tm_min'],
$parsed_date['tm_sec'],
$parsed_date['tm_mon'] + 1,
$parsed_date['tm_mday'],
$parsed_date['tm_year'] + 1900);
// Verify the conversion:
echo $orig_date . "\n";
echo date('d/m/y H:i:s', $nice_date);
$inDate = '180510_112440';
$date = strtotime('20'.substr($inDate,4,2).'-'.
substr($inDate,2,2).'-'.
substr($inDate,0,2).' '.
substr($inDate,7,2).':'.
substr($inDate,9,2).':'.
substr($inDate,11,2));
echo date('d-M-Y H:i:s',$date);
Assumes date will always be in exactly the same format, and always 21st century
list($d,$m,$y,$h,$i,$s)=sscanf("180510_112440","%2c%2c%2c_%2c%2c%2c");
echo "20$y-$m-$d $h:$i:$s";