I cant seem to figure out a way to format a string in perl to use in a MySQL DateTime() field.
my $time = "Sat Jun 29 11:20:28 2013 -0400"
and i need to format time so it can be entered into a MySQL DateTime() field
Format: YYYY-MM-DD HH:MM:SS
i plan to enter this using perl mysql module
$createQuery = "INSERT INTO something (dated) Values(?) ";
$sqlQuery = $dbh->prepare($createQuery);
$sqlQuery->execute($time);
You don't have to do any formatting yourself.
$time = time;
$createQuery = "INSERT INTO something (dated) Values( FROM_UNIXTIME( ? )) ";
$sqlQuery = $dbh->prepare($createQuery);
$sqlQuery->execute($time);
If you do really need a string and your data source is not a unix timestamp, just use any of the formats that MySQL understands.
$time = '2013-06-29 18:50:00';
$createQuery = "INSERT INTO something (dated) Values( FROM_UNIXTIME( ? )) ";
$sqlQuery = $dbh->prepare($createQuery);
$sqlQuery->execute($time);
You can use the core module Time::Piece which has been part of the Perl core since 5.9 : corelist .
use Time::Piece;
my $time = q(Sat Jun 29 11:20:39 2013 -0400);
my $t = Time::Piece->strptime($time, '%a %b %d %H:%M:%S %Y %z');
print $t->strftime("%Y-%m-%d %H:%M:%S\n");
If you don't have perl 5.9, Date::Manip will sort you:
$date_as_mysql_likes = UnixDate(ParseDate($your_date_here), '%Y-%m-%d %H:%M:%S');
Related
I have this php code:
(from my database class)
$q = "SELECT * FROM" . CON_TBL. " WHERE a = $b ORDER BY thedate DESC";
$result = mysqli_query($this->connection, $q);
The dates (unix timestamp) on the DB are:
1138322340
1617584160
1617673680
759952800
I got this result:
30-Jan-1994 12:00
05-Apr-2021 20:48
04-Apr-2021 19:56
26-Jan-2006 18:39
The first date should be the last:
05-Apr-2021 20:48
04-Apr-2021 19:56
26-Jan-2006 18:39
30-Jan-1994 12:00
Any ideas what's going on?
The thedate column was a VARCHAR instead of an INT, once I changed the column to INT the ORDER was corrected.
I am selecting three columns from my database with
$sql = "SELECT lnumber,violation,datetime FROM violators WHERE lnumber='".$lnumber."'";
and parsing the result into JSONArray and I am getting this result
{"lnumber":"2","violation":"Beating the red light","datetime":"2017-10-15 13:02:34"}
Now what I want to do is how can I parse the "datetime" field without the seconds?
Here is the full code:
$sql = "SELECT lnumber,violation,datetime FROM violators WHERE lnumber='".$lnumber."'";
$stmt = $con->prepare($sql);
$stmt->execute();
$stmt->bind_result($lnumber, $violation, $datetime);
while($stmt->fetch())
{
$temp = [
'lnumber'=>$lnumber,
'violation'=>$violation,
'datetime'=>$datetime
];
array_push($result, $temp);
}
echo json_encode($result);
SELECT DATE_FORMAT("2017-10-15 13:52:35", "%Y-%m-%d %H:%i")
Use %H for 2 digit 24 hour format (e.g. 08) or %k for 1 digit.
Reference:
https://www.w3schools.com/sql/func_mysql_date_format.asp
Try it here:
https://www.w3schools.com/sql/trymysql.asp?filename=trysql_func_mysql_date_format
SELECT DATE_FORMAT("2017-10-15 13:02:34", "%Y-%m-%d %h:%m");
=> 2017-10-15 01:10
MySQL DATE_FORMAT https://www.w3schools.com/sql/func_mysql_date_format.asp
This is if you want to get rid of the seconds during the data fetch.
I need some help with a project I'm working on.
There's a table with 2 dates: date1 and date2 (easier)
Now I need to show all rows where the current date is between date1 and date2.
What I have so far is:
$date = date(Y-m-d);
$sql = 'SELECT * FROM boekingen WHERE "$date" BETWEEN date1 AND date2';
but this doesn't work. Although if I replace "$date" with 2017-01-06 it does work. Now how do I solve this problem?
Thanks in advance!
You need to put quotes around the argument to date():
$date = date('Y-m-d');
And you need to wrap the string you assign to $sql in double quotes, otherwise the $date variable won't be expanded.
$sql = "SELECT * FROM boekingen WHERE '$date' BETWEEN date1 AND date2";
What is the difference between single-quoted and double-quoted strings in PHP?
The manual on date() is clear as to its syntax and using quotes around the arguments.
http://php.net/manual/en/function.date.php
Since yours has none, PHP is assuming you have them pre-defined as constants.
Error reporting would have thrown you the following:
Notice: Use of undefined constant Y - assumed 'Y' in /path/to/file.php on line x
Notice: Use of undefined constant m - assumed 'm' in /path/to/file.php on line x
Notice: Use of undefined constant d - assumed 'd' in /path/to/file.php on line x
Examples taken from Example #4 date() Formatting from the manual:
<?php
// Assuming today is March 10th, 2001, 5:16:18 pm, and that we are in the
// Mountain Standard Time (MST) Time Zone
$today = date("F j, Y, g:i a"); // March 10, 2001, 5:16 pm
$today = date("m.d.y"); // 03.10.01
$today = date("j, n, Y"); // 10, 3, 2001
$today = date("Ymd"); // 20010310
$today = date('h-i-s, j-m-y, it is w Day'); // 05-16-18, 10-03-01, 1631 1618 6 Satpm01
$today = date('\i\t \i\s \t\h\e jS \d\a\y.'); // it is the 10th day.
$today = date("D M j G:i:s T Y"); // Sat Mar 10 17:16:18 MST 2001
$today = date('H:m:s \m \i\s\ \m\o\n\t\h'); // 17:03:18 m is month
$today = date("H:i:s"); // 17:16:18
$today = date("Y-m-d H:i:s"); // 2001-03-10 17:16:18 (the MySQL DATETIME format)
?>
Use something like this
$date = date(Y-m-d);
$sql = 'SELECT * FROM boekingen WHERE STR_TO_DATE(\'$date'\', \'%m/%d/%Y\') BETWEEN date1 AND date2';
Make sure that date2 is greater than date1.
date = date(Y-m-d);
$sql = 'SELECT * FROM boekingen WHERE "$date"
That is the code on your question.
Using a single quote for string in php will not expand the variable.
Either use double quotes and single quotes around $date or concatenate eg
$sql = 'SELECT * FROM boekingen WHERE "' . $date .'"
Or sprintf
$sql = sprintf('SELECT * FROM boekingen WHERE "%s", $date)
i have a report which runs weekly on a friday doing some db queries where data is from monday to friday and producing a table with the results. I am having a problem when the report runs on a friday where the monday is last month. So for example last friday. Friday was the first of august, and the monday was the 28th of july. The below is the date and time portion of my script.
my $date = `date +%Y%m%d`;
chomp($date);
my $time = `date +%H%M%S`;
chomp($time);
my $day = `date +%A`;
chomp($day);
my $time = `date +%H%M%S`;
chomp($time);
my $dispTime = `date +%H:%M`;
chomp($dispTime);
# Set the Dates
my $end = $date;
my $start = $end;
# Check the day and define start and end dates.
if ($day eq "Friday") {
$start = $end - 5;
my #mytime=localtime;
my ($s, $min, $h, $d, $m, $y) = (0, 0, 0, $mytime[3], $mytime[4], $mytime[5]);
my $todayminus5 = strftime "%Y%m%d", $s, $min, $h, $d - 5, $m, $y;
$start = $todayminus5;
In my report logs it prints the date that was calculated and it printed this
Start Date = 2014080,
End Date = 20140801
Does anybody know why this doesnt seem to be able to calculate the date if its over two months?
You should use Time::Piece in conjunction with its sister module Time::Seconds. If you have a reasonably recent version of Perl then it should already be installed as it has been a core module since version 10 of Perl 5.
By the way, you need to subtract four days to get from Friday to the previous Monday!
use strict;
use warnings;
use Time::Piece;
use Time::Seconds 'ONE_DAY';
my $now = localtime;
if ($now->wdayname eq 'Fri') {
my $monday = ($now - ONE_DAY * 4)->strftime('%Y%m%d');
# etc.
}
I would rework the approach you're taking - you're doing multiple invocations of date which is probably a warning sign in the first place. You've got a whole lot of edge cases - subtracting '5' from your days will get you a negative number if it's early in the month - which will break things - but you'll have similar problems when the year changes.
I won't contradict the previous post, but I'd instead suggest you simplify:
my $ONE_DAY_s = 60 * 60 * 24;
my $now = time();
my $then = $now - 4*$ONE_DAY_s;
my ( $sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($now);
$year += 1900;
print "Now: $year $mon $mday\n";
( $sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($then);
$year += 1900;
print "Then: $year $mon $mday\n";
(transcribed, rather than pasted so beware typos).
You can use $wday to figure out if it's a friday.
Modules exist to do this as well though - I would be very wary of using repeated invocations of an external command, and then trying to mangle the results.
You can use the Datetime module to get the start date and end date
Example:
use strict;
use warnings;
use DateTime;
my $today_date = DateTime->today(); # Current date (Friday)
my $old_date = $today_date->clone()->subtract(days => 4); # First DoW (Monday)
print $today_date, "\n";
print $old_date, "\n";
Outputs:
2014-08-04T00:00:00
2014-07-31T00:00:00
If I have a MySQL date as follows 2012-07-29 22:02:50, and I want this to be formatted to Jul 29 2012, is there an easy way to do this using a SELECT statement?
Currently my sql statement looks like this:
$rs = mysql_query("SELECT Id, DATE_FORMAT(Date,\"%Y-%m-%d\") AS Date FROM infoTable WHERE credential = '$credential'");
This outputs 2012-07-29
Try this:
$rs = mysql_query("SELECT Id, DATE_FORMAT(Date,\"%b %e %Y\") AS Date FROM infoTable WHERE credential = '$credential'");
Source
Change the DATE_FORMAT expression to:
DATE_FORMAT(Date,\"%b %e %Y\")
You can view all the possible formatting options at the DATE_FORMAT reference page.
$rs = mysql_query("SELECT Id, DATE_FORMAT(Date,\"%b %e %Y\") AS Date FROM infoTable WHERE credential = '$credential'");
http://www.w3schools.com/sql/func_date_format.asp