I'm quite new to php and have been reading Larry Ullman book to develop a basic db site.
I have used the YUI Calendar pop up date picker to add a date to a text field called"date". The date format it enters is eg Thursday, 7 May 2009
I have tried many different ways to try and enter the date in to mysql db but it remains at 00 00 00 00 00 00
This is the code related to the date field I have,
// Check for a Date.
if (eregi ("^([0-9]{2})/([0-9]{2})/([0-9]{4})$", $_POST['date'],)) {
$p = escape_data($_POST['date'],);
} else {
$p = FALSE;
echo '<p><font color="red">Please enter a valid Date!</font></p>';
}
// Add the URL to the urls table.
$query = "INSERT INTO urls (url, title, description, date) VALUES ('$u', '$t', '$d', '$p')";
$result = #mysql_query ($query); // Run the query.
$uid = #mysql_insert_id(); // Get the url ID.
if ($uid > 0) { // New URL has been added.
I think I have provided all pertinent information but again apologies if this isn't helpful and I will do my best to provide yo with any other information you may require.
Thanks - Sean
If the format that your date picker is passing in is "Thursday, 7 May 2009", then the strtotime() and date() functions should work to give you a valid date to pass to MySQL:
$p = date("Y-m-d H:i:s",strtotime('Thursday, 7 May 2009'));
If your database field is a DATE, you probably only want the "Y-m-d" part. If it's a DATETIME, you'll want the "H:i:s" as well.
You probably need to format the date in the way that mysql expects it for that datatype, or else it cannot recognize it. You could use a regex or similar method to extract the component parts and format it according to the format of the MySQL DATETIME type.
EDIT: See http://dev.mysql.com/doc/refman/5.0/en/datetime.html for said format. Also, you might be better off storing the date/time as a unix timestamp, as that usually is easier to maintain.
the date format in mysql is YYYY-MM-DD, so change the way you accept data on php
if (eregi ("^([0-9]{2})/([0-9]{2})/([0-9]{4})$", $_POST['date'],)) {
$p = escape_data($_POST['date'],);
} else {
$p = FALSE;
echo 'Please enter a valid Date!';
Should be
if (eregi ("^([0-9]{4}/([0-9]{2})/([0-9]{2}))$", $_POST['date'],)) {
$p = escape_data($_POST['date'],);
} else {
$p = FALSE;
echo 'Please enter a valid Date!';
Related
I'm trying to write a function in Powershell where I calculate the age of the user based on the birthdate. So it should probably be currentdate - birthdate and put the difference in years. I'm getting stuck however, on the formating of these dates because the user has to input their birthdate.
Function getAge ($birthDate)
{
$currentDate = Get-Date
$age = $currentDate - $birtDate
Write-Host "Your age is $age"
}
getAge 24-01-1991
Your function is almost there, except for the fact that it creates and returns a TimeSpan object with the difference between the current and the given date.
Try
function Get-Age {
param (
[Parameter(Mandatory = $true)]
[datetime]$birthDate
)
$currentDate = Get-Date
$age = $currentDate - $birthDate
# use the ticks property from the resulting TimeSpan object to
# create a new datetime object. From that, take the Year and subtract 1
([datetime]::new($age.Ticks)).Year - 1
}
# make sure the BirthDate parameter is a valid DateTime object
Get-Age ([datetime]::ParseExact('24-01-1991', 'dd-MM-yyyy', $null))
First you need to convert the input parameter $birthDate, currently a string, to a DateTime object, for that you can use the ParseExact(..) method. Then you need to decide which type of date format your function will accept, I have added a ValidatePattern attribute to the function so that currently only accepts the pattern shown in your question, this however can be updated so that the function takes more than one format (ParseExact(..) can also parse multiple formats). Lastly, you're correct with Current Date - Birth Date, this will get us a TimeSpan object which has a .Days property, we can use the value of the property and divide it by the number of days in a year to obtain the user's age.
function getAge {
[cmdletbinding()]
param(
[ValidatePattern('^(\d{2}-){2}\d{4}$')]
[string]$birthDate
)
$parsedDate = [datetime]::ParseExact(
$birthDate,
'dd-MM-yyyy',
[cultureinfo]::InvariantCulture
)
[int] $age = ([datetime]::Now - $parsedDate).Days / 365
Write-Host "Your age is $age"
}
getAge 24-01-1991
result = connect.query("SELECT * FROM data WHERE event_type = 'ALARM_OPENED' AND severity = '2'")
equipments = result.map { |print_this| [print_this['sourcetime'], print_this['description']] }
p equipments
The Datatype for sourcetime in MySQL workbench is set to TIME
The result I get is 2000-01-01 12:00:04 +0100
I would like to get only the time 12:00:04 and drop the date and +0100
Two steps are necessary to achieve this:
Time.parse the string returned from your database into an instance of Time.
Use Time#strftime to format the instance of Time into the desired output format.
To just display the hours, minutes and seconds of a time (without the date and timezone information) use the '%H:%M:%S' directive (see the docs for more examples).
require 'time' # `Time.parse` is not Ruby Core but from the Standard Library
equipments = result.map do |record|
[
Time.parse(record['sourcetime']).strftime('%H:%M:%S'),
record['description']
]
end
Can you try strftime("%I:%M%p")
equipments = result.map { |print_this| print_this.sourcetime.strftime("%I:%M%p") }
function details_klanten($idKlant,$start,$eind){
$this->db->select(' Project.idProject,
Project.Titel,
Project.idProjecttype,
Project.Begindatum,
Project.Deadline,
Project.idKlant,
Projecttypes.idProjecttypes,
Projecttypes.Type,
Werknemer.idWerknemer,
Werknemer.Voornaam,
Statusproject.idStatusProject,
Statusproject.Soort,
Klant.Naam');
$this->db->order_by('Titel', 'asc');
$this->db->from('Project');
$this->db->join('Klant', 'Klant.idKlant = Project.idKlant');
$this->db->join('Projecttypes', 'Projecttypes.idProjecttypes = Project.idProjecttype');
$this->db->join('Werknemer', 'Werknemer.idWerknemer = Project.idWerknemer');
$this->db->join('Statusproject', 'Statusproject.idStatusProject = Project.idStatusProject');
if ($idKlant > 0){
$this->db->where('Klant.idKlant',$idKlant);
$this->db->where('Project.Begindatum >',$start);
$this->db->where('Project.Deadline <',$eind);
}
$query = $this->db->get();
if($query->num_rows()>0){
return $query->result();
}
else{
return false;
}
}
The project.Begindatum and the Project.Deadline are varchar(10). So it looks at the first two numbers not the full date. For example:
$start = '01-04-2014';
'Project.Begindatum' = (Varchar)'02-03-2014'.
Then it will be shown because
it looks only to the '01'(-04-2014) and the '02'(-03-2014)
Use mysql's STR_TO_DATE() function and also pass third parameter in where() as FALSE
$this->db->where("STR_TO_DATE(Project.Begindatum,'%d-%m-%Y') >",$start,FALSE);
$this->db->where("STR_TO_DATE(Project.Deadline,'%d-%m-%Y') <",$eind,FALSE);
Its better to change the type of your columns to store in standard format use date type to store dates in database ,Using STR_TO_DATE with format %d-%m-%Y then the value stored in table should have %d-%m-%Y format otherwise it won't work ,it should be compared to $start = '2014-04-01';,otherwise you need another function i.e DATE_FORMAT to format it like 01-04-2014
$this->db->where("DATE_FORMAT(STR_TO_DATE(Project.Begindatum,'%d-%m-%Y'),'%d-%m-%Y') >",
$start,FALSE);
$this->db->where("DATE_FORMAT(STR_TO_DATE(Project.Deadline,'%d-%m-%Y'),'%d-%m-%Y') <"
,$eind,FALSE);
Reminder: STR_TO_DATE(...) output format: Y-m-d
Example: 2020-12-24
Therefore: $start and $eind format: Y-m-d
Example: 2020-12-31
$this->db->where("STR_TO_DATE(Project.Begindatum, '%m-%d-%Y') >",$start);
$this->db->where("STR_TO_DATE(Project.Deadline, '%m-%d-%Y') <",$eind);
I hope this helps you too. Peace.
I am using a DATE field in my MYSQL table, and pulling it through on a php page. The problem is it comes out as "2011-04-23"
Is there a way I can reformat this as 23/04/2011?
Thanks :)
date("d/m/Y", strtotime("2011-04-23"));
that should do it
date()
strtotime()
DATE_FORMAT(date,format)
Look here: http://dev.mysql.com/doc/refman/5.0/es/date-and-time-functions.html
Assuming variable $date contains your MySQL data:
$date = '2011-04-23';
$timezone = 'Europe/London'; // this is optional argument
$formatted = DateTime::createFromFormat('Y-m-d', $date, new DateTimeZone($timezone));
// or without the optional timezone - where php will assume the default timezone from your OS
$formatted = DateTime::createFromFormat('Y-m-d', $date);
echo $formatted->('d/m/Y');
I was trying to convert this format of String to Date and was unsuccessfull
"23-DEC-2008" to a Date Object ,it looks like its not accepting "-" and i could see NULL in the date object after formatting .
Can somebody let me know if u have come across this problem .
Thanks ,
Sudeep
The "-" shouldn't be an issue. I've converted SQL timestamp strings to Date objects with no problem (the format of SQL date strings is YYYY-MM-DD). What is the format string you're using? Try using the format string "DD-MMM-YYYY" and see if that works.
Edit
Sorry, my solution only applies to the DateFormatter class from Flex, and not Actionscript. After looking at the documentation for the Actionscript Date class I saw the following:
The year month and day terms can be separated by a forward slash (/) or by spaces, but never by a dash (-). (1)
If you're stuck using straight Actionscript, it looks as if you'll have to write your own parse method that accepts the "-".
this sort of works ...
public function parse(source:String):Date {
var ret:Date = new Date(0, 0, 0, 0, 0, 0, 0);
var parts:Array = source.split("-");
ret.fullYear = Number(parts[2]);
ret.setDate(Number(parts[0]));
var month:int = "jan,feb,mar,apr,may,jun,jul,aug,sep,oct,now,dec".split(",").indexOf(String(parts[1]).toLowerCase());
if (month == -1) throw "could not parse month";
ret.setMonth(month);
return ret;
}
but really, i don't like it ... if 'DEC' were 'Dec' , then
Date.parse("23-Dec-2008".split("-").join(" "))
would work ... but still ... i think, you should get something more robust ...
greetz
back2dos