Select date mysql request - php

I have the request below in a php file. I'm trying to get a date in this format: MONTHS-currentMonth-currentYear
$sql = "SELECT DAY(ADDDATE(`dateDebutC`, `dureeC`)) AS MONTHS FROM normalW WHERE id = '$id'";

If you want to format the date after returning the values from your sql query, then you can use the PHP date_format() function. Assuming you store the months value in a variable, let's call it $date:
echo date_format($date,'Y-m-d'); // Or whatever format you want to display
To add the current month and current year to that string, you can use the date() function:
$current_month = date(m); // prints current month in numeric format (01-12)
$current_year = date(Y); // prints current year as a 4-digit representation
$new_date = $date . '-' . $current_month . '-' . $current_year;
See https://www.w3schools.com/php/func_date_date.asp for a list of all parameters. And as a friendly reminder, please ensure that you are using mysqli rather than mysql, which is deprecated.

To get current month and year you can use GETDATE function in sql
$sql = "SELECT MONTH(ADDDATE(`dateDebutC`, `dureeC`))AS MONTHS,MONTH(GETDATE()) as curmonth,YEAR(GETDATE()) as curyear FROM normalW where id = '$id'";

Whatever this comes through as in result, for example, however you bind it:
$date = '2014-04-15 10:10:11';
$buildDate = new DateTime(strtotime($date));
$dowMonthDayYear = $buildDate->format('l F j, Y');
echo dowMonthDayYear // turns as April 15th, 2014
You can lookup datetime in php manual for other formats theres tons

Related

Store date directly in PHP variable

I want to store a specific date in a variable. If stored like $x="01/01/2016" it is acting as a string from which I cannot extract a part, like from getdate() year, month, day of the month, etc.
Use the DateTime object:
$dateTime = new DateTime('2016/01/01');
To get only parts of the date you can use the format method:
echo $dateTime->format('Y'); // it will display 2016
If you need to create it from the format you wrote in the question, then you can use the factory method createFromFormat:
$dateTime = DateTime::createFromFormat('d/m/Y', '01/01/2016');
echo $dateTime->format('Y/m/d');
This is work for me
$date = '20/May/2015:14:00:01';
$dateInfo = date_parse_from_format('d/M/Y:H:i:s', $date);
$unixTimestamp = mktime(
$dateInfo['hour'], $dateInfo['minute'], $dateInfo['second'],
$dateInfo['month'], $dateInfo['day'], $dateInfo['year'],
$dateInfo['is_dst']
);
this is what you are looking for http://php.net/manual/en/class.datetime.php
You can use $myDate = new DateTime('01/01/2016'); to declare date. To get year, month and date from the specified date, use echo $myDate->format('d m Y');
Change the format based on your need. To know more about date format refer

Creating a Timestamp from a URL string

I have read the manual - but can't seem to find what I need. I don't need the actual date - I need the date I tell it is from the URL
This is what I have currently:
//create search string for posts date check
if($Day <= 9) {//ensure day is dual digit
$fix = 0;
$Day = $fix . $Day;
}
$Day = preg_replace("/00/", "/0/", $Day);
$date = $_GET["Year"];
$date .= "-";
$date .= $_GET["Month"];
$date .= "-";
$date .= $_GET["Day"];
$currently = mktime (0,0,0,$Month,$Day,$Year,0); //create a timestamp from date components in url feed
//create display date from timestamp
$dispdate = date("l, j F Y",$currently);
When I echo $date it reads correctly for the variable string supplied in the URL but $dispdate always returns the current day that it actually is today. I need $currently to be the timestamp of the date in the URL too.
You seem to construct a valid, readable datestring from the GET parameters. Use
$currently = strtotime($date).
It will return a timestamp that you can use to create the $dispdate like you already do with the date function.
Seems like not all the OP's code was posted, so this is based on what is known.
In the line:
mktime (0,0,0,$Month,$Day,$Year,0)
You are using variables that aren't shown to us (so we must assume are not being set to anything). Above this line you are building a "$date" variable with the URL parameters. This is what should be used in your mktime function.
You could use a Datetime object, pass the given parameters and format the output anyway you want.
<?php
//replace with GET params
$year = 2015;
$month = 10;
$day = 01;
$datetime = new Datetime($year.'-'.$month.'-'.$day);
echo $datetime->format('Y-m-d');
?>

Time stored in DB minus 2 weeks

I would like to show the date 2 weeks before the date stored in a DB
The date isnt stored in Timestamp, it is stored like 01/01/2015
I have tried the below but this isnt working, can anyone help?
echo date('$valid_to', strtotime("-2 week"));
I would use DateTime class instead.
// timezone is optional
$date = new DateTime($valid_to, new DateTimeZone('Europe/Vilnius'));
echo $date->modify('-2 weeks');
// there you have your wanted date
$valid_date = $date->format('Y-m-d');
Then would recommend STR_TO_DATE mysql function to convert to correct timestamp.
For example:
$query = "SELECT * FROM table WHERE time_col <= STR_TO_DATE('" . $valid_date . "', '%Y-%m-%d')";

Adjust a PHP date to the current year

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"

How to determine if a date is more than three months past current date

I am getting a date back from a mysql query in the format YYYY-MM-DD.
I need to determine if that is more than three months in the past from the current month.
I currently have this code:
$passwordResetDate = $row['passwordReset'];
$today = date('Y-m-d');
$splitCurrentDate = explode('-',$today);
$currentMonth = $splitCurrentDate[1];
$splitResetDate = explode('-', $passwordResetDate);
$resetMonth = $splitResetDate[1];
$diferenceInMonths = $splitCurrentDate[1] - $splitResetDate[1];
if ($diferenceInMonths > 3) {
$log->lwrite('Need to reset password');
}
The problem with this is that, if the current month is in January, for instance, giving a month value of 01, and $resetMonth is November, giving a month value of 11, then $differenceInMonths will be -10, which won't pass the if() statement.
How do I fix this to allow for months in the previous year(s)?
Or is there a better way to do this entire routine?
Use strtotime(), like so:
$today = time(); //todays date
$twoMonthsLater = strtotime("+3 months", $today); //3 months later
Now, you can easily compare them and determine.
I’d use PHP’s built-in DateTime and DateInterval classes for this.
<?php
// create a DateTime representation of your start date
// where $date is date in database
$resetDate = new DateTime($date);
// create a DateIntveral representation of 3 months
$passwordExpiry = new DateInterval('3M');
// add DateInterval to DateTime
$resetDate->add($passwordExpiry);
// compare $resetDate to today’s date
$difference = $resetDate->diff(new DateTime());
if ($difference->m > 3) {
// date is more than three months apart
}
I would do the date comparison in your SQL expression.
Otherwise, PHP has a host of functions that allow easy manipulation of date strings:
PHP: Date/Time Functions - Manual

Categories