I have the code:
$month = DateTime::createFromFormat('m/Y', $date);
if ($month) {
$month = $month -> format('01/m/Y');
}
echo "From ".$startMonth." to ".$endMonth = date("t/m/Y", strtotime($month));
when $date is a string like "05/2015".
This returns:
From 01/05/2015 to 31/01/2015
But for some reason the month is coming up as 01 when it should be 05?
Why is it doing this? It should be
From 01/05/2015 to 31/05/2015
Besides the unnecessary chopping and changing between DateTime objects and unix timestamps (when you could do the whole thing using DateTime objects.... you're passing a formatted date of '01/m/Y' to strtotime()... the / indicates to the strtotime() function that the date is in US date format (mm/dd/yy): and you should use '01-m-Y' (with a -) for dd-mm-YYYY if you want to tell strtotime() that it's a European format date.
See the "localized notations" table on the PHP Docs page for an explanation of formats accepted by strtotime()
However, doing the whole thing using DateTime objects:
$date = '4/2015';
$month = DateTime::createFromFormat('m/Y', $date);
echo "From " . $month->format('01/m/Y') . " to ". $month->format('t/m/Y');
Related
I have SQLite DB one table contains datetime field
with datatype "timestamp" REAL value is 18696.0
attach image for table structure
So, I want this 18696.0 value to be converted into MySQL Y-m-d format and result should be 2021-03-10
I have didn't found any solution online. any help would be appreciated.
SQLite timestamp converted into MySQL timestamp.
EDIT: Thankyou for updating your question with the correct number and what date it should represent.
You can achieve what you need with a function that adds the days onto the Unix Epoch date:
function realDateToYmd($real, $outputFormat='Y-m-d')
{
$date = new DateTime('1970-01-01');
$date->modify('+' . intval($real) . ' days');
return $date->format($outputFormat);
}
echo realDateToYmd('18696.0');
// returns 2021-03-10
SQLite dates stored in REAL data type stores dates as a Julian Day.
From https://www.sqlite.org/datatype3.html
REAL as Julian day numbers, the number of days since noon in Greenwich on November 24, 4714 B.C. according to the proleptic Gregorian calendar.
PHP has a jdtogregorian function, in which one comment has a handy function to convert to ISO8601 dates:
function JDtoISO8601($JD) {
if ($JD <= 1721425) $JD += 365;
list($month, $day, $year) = explode('/', jdtogregorian($JD));
return sprintf('%+05d-%02d-%02d', $year, $month, $day);
}
echo JDtoISO8601('17889.0');
// Results in -4664-11-16
The results don't exactly look right, is it definitely 17889.0 in SQLite?
If this float number 18696.0 represents the number of days since 1970-01-01 then the date can also be calculated like this:
$days = 18696.0;
$dt = date_create('#'.((int)($days * 86400)));
$mysqlDate = $dt->format('Y-m-d'); //"2021-03-10"
background information
Or simply with gmdate:
$mySqlDate = gmdate('Y-m-d',$days*86400);
The days are simply converted into seconds to get a valid timestamp for gmdate.
Try this:
<?php
echo date('Y-m-d H:i:s', 17889);
?>
Output:
1970-01-01 04:58:09
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
I have a PHP date in a database, for example 8th August 2011. I have this date in a strtotime() format so I can display it as I please.
I need to adjust this date to make it 8th August 2013 (current year). What is the best way of doing this? So far, I've been racking my brains but to no avail.
Some of the answers you have so far have missed the point that you want to update any given date to the current year and have concentrated on turning 2011 into 2013, excluding the accepted answer. However, I feel that examples using the DateTime classes are always of use in these cases.
The accepted answer will result in a Notice:-
Notice: A non well formed numeric value encountered......
if your supplied date is the 29th February on a Leapyear, although it should still give the correct result.
Here is a generic function that will take any valid date and return the same date in the current year:-
/**
* #param String $dateString
* #return DateTime
*/
function updateDate($dateString){
$suppliedDate = new \DateTime($dateString);
$currentYear = (int)(new \DateTime())->format('Y');
return (new \DateTime())->setDate($currentYear, (int)$suppliedDate->format('m'), (int)$suppliedDate->format('d'));
}
For example:-
var_dump(updateDate('8th August 2011'));
See it working here and see the PHP manual for more information on the DateTime classes.
You don't say how you want to use the updated date, but DateTime is flexible enough to allow you to do with it as you wish. I would draw your attention to the DateTime::format() method as being particularly useful.
strtotime( date( 'd M ', $originaleDate ) . date( 'Y' ) );
This takes the day and month of the original time, adds the current year, and converts it to the new date.
You can also add the amount of seconds you want to add to the original timestamp. For 2 years this would be 63 113 852 seconds.
You could retrieve the timestamp of the same date two years later with strtotime() first parameter and then convert it in the format you want to display.
<?php
$date = "11/08/2011";
$time = strtotime($date);
$time_future = strtotime("+2 years", $time);
$future = date("d/m/Y", $time_future);
echo "NEW DATE : " . $future;
?>
You can for instance output it like this:
date('2013-m-d', strtotime($myTime))
Just like that... or use
$year = date('Y');
$myMonthDay = date('m-d', strtotime($myTime));
echo $year . '-' . $myMonthDay;
Use the date modify function Like this
$date = new DateTime('2011-08-08');
$date->modify('+2 years');
echo $date->format('Y-m-d') . "\n";
//will give "2013-08-08"
I'm having date 20/12/2001 in this formate . i need to convert in following format 2001/12/20 using php .
$var = explode('/',$date);
$var = array_reverse($var);
$final = implode('/',$var);
Your safest bet
<?php
$input = '20/12/2001';
list($day, $month, $year) = explode('/',$input);
$output= "$year/$month/$day";
echo $output."\n";
Add validation as needed/desired. You input date isn't a known valid date format, so strToTime won't work.
Alternately, you could use mktime to create a date once you had the day, month, and year, and then use date to format it.
If you're getting the date string from somewhere else (as opposed to generating it yourself) and need to reformat it:
$date = '20/12/2001';
preg_replace('!(\d+)/(\d+)/(\d+)!', '$3/$2/$1', $date);
If you need the date for other purposes and are running PHP >= 5.3.0:
$when = DateTime::createFromFormat('d/m/Y', $date);
$when->format('Y/m/d');
// $when can be used for all sorts of things
You will need to manually parse it.
Split/explode text on "/".
Check you have three elements.
Do other basic checks that you have day in [0], month in [1] and year in [2] (that mostly means checking they're numbers and int he correct range)
Put them together again.
$today = date("Y/m/d");
I believe that should work... Someone correct me if I am wrong.
You can use sscanf in order to parse and reorder the parts of the date:
$theDate = '20/12/2001';
$newDate = join(sscanf($theDate, '%3$2s/%2$2s/%1$4s'), '/');
assert($newDate == '2001/12/20');
Or, if you are using PHP 5.3, you can use the DateTime object to do the converting:
$theDate = '20/12/2001';
$date = DateTime::createFromFormat('d/m/Y', $theDate);
$newDate = $date->format('Y/m/d');
assert($newDate == '2001/12/20');
$date = Date::CreateFromFormat('20/12/2001', 'd/m/Y');
$newdate = $date->format('Y/m/d');
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";