My first OOP\Class attempt: Date Conversion.

Coding Critique is the place to post source code for peer review by other members of DevNetwork. Any kind of code can be posted. Code posted does not have to be limited to PHP. All members are invited to contribute constructive criticism with the goal of improving the code. Posted code should include some background information about it and what areas you specifically would like help with.

Popular code excerpts may be moved to "Code Snippets" by the moderators.

Moderator: General Moderators

Post Reply
User avatar
stakes
Forum Commoner
Posts: 48
Joined: Tue Jun 12, 2007 12:05 pm

My first OOP\Class attempt: Date Conversion.

Post by stakes »

I just threw myself into the world of OOP. Well... I'm guessing this code is far from what one would called "real" OOP, but it's a start for me at least. So now i came here to be bashed around and get told what a useless piece of code i just wrote :). However i already put this into use on some of my scripts where i have scattered functions all over for converting different dates into "readable" figures on posts on guestbooks, messages, news items. Etc. Anyways, Here it is:

Code: Select all

/**

class DateConversion
-------------------------

A class for converting all kinds of timestamps
into differnt formats throughout the website.

Raw input is format: YYYYMMDDHHIISS

Y: YEAR
M: MONTH
D: DAY
H: HOUR
I: MINUTE
S: SECOND

**/

class DateConversion	{
	
		public $year;
		public $month;
		public $day;
		public $hour;
		public $minute;
		public $second;
	
		public $monthNumbers = array	(
										"01", 
										"02", 
										"03", 
										"04", 
										"05", 
										"06",
										"07", 
										"08", 
										"09", 
										"10", 
										"11", 
										"12"
								);
							
		public $monthNames = 	array	(
										"January",
										"February",
										"March",
										"April",
										"May",
										"June",
										"July",
										"August",
										"September",
										"October",
										"November",
										"December"
								);
							
		function dateConversion()			{
			
			
		}

		public function getYear($dateInput)		{
			
			$this->year = substr($dateInput,0,4);
			return $this->year;
			
		}
		
		public function getMonth($dateInput)		{
			
			$this->month = substr($dateInput,4,2);
			return $this->month;
			
		}
		
		public function getMonthName($dateInput)	{
			
			$this->month = $this->getMonth($dateInput);
			$this->month = str_replace($this->monthNumbers,$this->monthNames,$this->month); 
			return $this->month;
			
		}
		
		public function getDay($dateInput)			{
			
			$this->day = substr($dateInput,6,2);
			$zero_length = strspn($this->day,  "0"); /* Remove leading zero */
   			$this->day = substr($this->day,  $zero_length); 
   			return $this->day;
			
		}

		
		public function getHour($dateInput)		{
			
			$this->hour = substr($dateInput,8,2);
			return $this->hour;
			
		}
		
		public function getMinute($dateInput)		{
			
			$this->minute = substr($dateInput,10,2);
			return $this->minute;
			
		}
		
		public function getSecond($dateInput)		{
			
			$this->second = substr($dateInput,12,2);
			return $this->second;
			
		}
}

/* Usage: Let's use the date\time right now as an example */

$today = date("YmdHis");

echo "Raw output: $today\n<br />"; 

/* Creating the date conversion object */

$dateOuput 	= new DateConversion();

echo "\n<br />";
echo $dateOuput->getYear($today);
echo "\n<br />";
echo $dateOuput->getMonth($today);
echo "\n<br />";
echo $dateOuput->getDay($today);
echo "\n<br />";
echo $dateOuput->getHour($today);
echo "\n<br />";
echo $dateOuput->getMinute($today);
echo "\n<br />";
echo $dateOuput->getSecond($today);
echo "\n<br />";
echo $dateOuput->getMonthName($today);
Now for some questions :)

1) I'm trying to figure out a way to extract what day of the week the actual date is just based on the raw input. Any ideas?

[s]
2) I'm using public functions and variables here, i tried converting everything to "private" and it still works. I think i'm misunderstanding the concept here. What did i actually change? And which should i use?[/s] Ignore all of this. It didn't work, i got it now.
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: My first OOP\Class attempt: Date Conversion.

Post by Christopher »

stakes wrote:I just threw myself into the world of OOP.
Not quite there yet. This is just procedural code namespaced in a class construct.

Code: Select all

echo "\n<br />";
echo $dateOuput->getYear($today);
echo "\n<br />";
echo $dateOuput->getMonth($today);
echo "\n<br />";
echo $dateOuput->getDay($today);
echo "\n<br />";
echo $dateOuput->getHour($today);
echo "\n<br />";
echo $dateOuput->getMinute($today);
echo "\n<br />";
echo $dateOuput->getSecond($today);
echo "\n<br />";
echo $dateOuput->getMonthName($today);
I would recommend:

Code: Select all

$dateOuput 	= new DateConversion($timestamp=null);     // null means today
ech $dateOuput->getYear();
(#10850)
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Re: My first OOP\Class attempt: Date Conversion.

Post by pickle »

arborint wrote:

Code: Select all

$dateOuput  = new DateConversion($timestamp=null);     // null means today
ech $dateOuput->getYear();
I'm sure he means:

Code: Select all

echo $dateOuput->getYear();
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
User avatar
s.dot
Tranquility In Moderation
Posts: 5001
Joined: Sun Feb 06, 2005 7:18 pm
Location: Indiana

Post by s.dot »

Your class members shouldn't be public. In fact I don't really see a reason for them to ever be public. You should know where you're setting them. Private would work here. Passing a date to a __construct() method would probably be ideal in this circumstance, or use of __get() and __set().
Set Search Time - A google chrome extension. When you search only results from the past year (or set time period) are displayed. Helps tremendously when using new technologies to avoid outdated results.
User avatar
stakes
Forum Commoner
Posts: 48
Joined: Tue Jun 12, 2007 12:05 pm

Re: My first OOP\Class attempt: Date Conversion.

Post by stakes »

arborint wrote:
stakes wrote:I just threw myself into the world of OOP.
Not quite there yet. This is just procedural code namespaced in a class construct.
Lets just call it my first attempt on a namespaced class construct then :)

scottayy:

1) I changed the class members to private, because they'll never be accessed outside the class, correct?

2) The functions have to be public because i access them outside the class (i.e echo $dateOuput->getYear() ), correct?

3) Is public the default "visibility" for class members\functions ?

4) I don't see how passing the date to a __construct() method would make the class better. Could you please clarify? Please keep in mind
that I'm new to all this if you attempt on explaining :lol:
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: My first OOP\Class attempt: Date Conversion.

Post by Christopher »

stakes wrote:4) I don't see how passing the date to a __construct() method would make the class better. Could you please clarify? Please keep in mind
that I'm new to all this if you attempt on explaining :lol:
Remember, an object is data with associated method that manipulate that data. So your class should be the date and the methods manipulate that date. You want your object to be useful when created, so pass it a date to initialize it, or have it default to now.
(#10850)
User avatar
stakes
Forum Commoner
Posts: 48
Joined: Tue Jun 12, 2007 12:05 pm

Post by stakes »

Ok i made some improvements (i hope :oops: ). I also added a new function to calculate weekday on given date based on the epoch timestamp, which is calculated in the constructor. However from what i've learned it's not very "clever" to use due to the 32-bit limitation issue?! (any inputs on this?) I also let the getDate take care of naming the months instaed of having my own monthNames array. But anyways, here goes:

Code: Select all

<?php

/**

class DateConversion
-------------------------

A class for converting all kinds of timestamps
into differnt formats throughout the website.

Raw input is format: YYYYMMDDHHIISS

Y: YEAR
M: MONTH
D: DAY
H: HOUR
I: MINUTE
S: SECOND

**/

class DateConversion    {
       
                private $year;
                private $month;
                private $day;
                private $hour;
                private $minute;
                private $second;
		private $epochDate;
		private $weekDay;
		private $dateInput;
												 
		function __construct($dateInput)		{
				
			$this->dateInput = $dateInput;
			$this->epochDate =  mktime (
									$this->getHour($dateInput), 
									$this->getMinute($dateInput), 
									$this->getSecond($dateInput), 
									$this->getMonth($dateInput), 
									$this->getDay($dateInput), 
									$this->getYear($dateInput)
									);
		}


                public function getYear()         			{
                       
                        $this->year = substr($this->dateInput,0,4);
                        return $this->year;
                       
                }
               
                public function getMonth()					{
                       
                        $this->month = substr($this->dateInput,4,2);
                        return $this->month;
                       
                }

               
                public function getDay()					{
                       
                        $this->day = substr($this->dateInput,6,2);
                 		return $this->day;
                       
                }

                public function getHour() 					{
                       
                        $this->hour = substr($this->dateInput,8,2);
                        return $this->hour;
                       
                }
               
                public function getMinute() 				{
                       
                        $this->minute = substr($this->dateInput,10,2);
                        return $this->minute;
                       
                }
               
                public function getSecond()      			{
                       
                        $this->second = substr($this->dateInput,12,2);
                        return $this->second;
                       
                }
	
				public function getWeekDay()				{
                       
					$this->dateArray = getDate($this->epochDate);
					$this->weekDay = $this->dateArray['weekday'];
					return $this->weekDay;
					
                }
				
				public function getMonthName()				{
                       
					$this->dateArray = getDate($this->epochDate);
					$this->monthName = $this->dateArray['month'];
					return $this->monthName;
					
                }
				
}

/* Usage: Let's my birthdate as an example O_o */

$birthDate = "19871128152400";

echo "Raw input: $birthDate\n<br />";

/* Creating the date conversion object */

$dateOuput = new DateConversion($birthDate);

echo "\n<br />I was born ";
echo $dateOuput->getHour();
echo ":";
echo $dateOuput->getMinute();
echo " on ";
echo $dateOuput->getMonthName(); 
echo " ";
echo $dateOuput->getDay();
echo " in ";
echo $dateOuput->getYear();
echo ". It was a ";
echo $dateOuput->getWeekDay();
So the example usage gives me.

Code: Select all

Raw input: 19871128152400

I was born 15:24 on November 28 in 1987. It was a Saturday
Again, any constructive comments, suggestions would be nice.

thanks in advance.
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Post by Christopher »

Better. You don't need parameters here:

Code: Select all

$this->epochDate =  mktime (
                                                                        $this->getHour($dateInput),
                                                                        $this->getMinute($dateInput),
                                                                        $this->getSecond($dateInput),
                                                                        $this->getMonth($dateInput),
                                                                        $this->getDay($dateInput),
                                                                        $this->getYear($dateInput)
This class only deals with dates in your packed format. What about 'yyyy-mm-dd hh:mm:ss' style from databases or timestamp style from the system. Does the constructor accept several styles and figures it out? Or pass it a type with the date? Or separate methods to set the date in different styles?
(#10850)
User avatar
stakes
Forum Commoner
Posts: 48
Joined: Tue Jun 12, 2007 12:05 pm

Post by stakes »

Thanks for your help and suggestions arborint!

I modified the constructor to also deal with the mysql TIMESTAMP format (YYYY-MM-DD HH:MM:SS)

Code: Select all

public function __construct($dateInput)                
                {
                	$dateInput = str_replace(' ','',$dateInput);
                	$dateInput = str_replace('-','',$dateInput);
                	$dateInput = str_replace(':','',$dateInput);
                        $this->dateInput = $dateInput;
                        $this->epochDate =  mktime 	(
	                                                $this->getHour(),
	                                                $this->getMinute(),
	                                                $this->getSecond(),
	                                                $this->getMonth(),
	                                                $this->getDay(),
	                                                $this->getYear()
	                                                );
                }
However this brings me to another question. I'm currently using INT(14) to store timestamps, and so i handle all the required "date-calculations" on the PHP side, is this a generally a "bad way" of doing it? In a performance and efficiency perspective should i rather use the TIMESTAMP for that those fields and do calculations SQL query wise? I hope it makes sense what I'm trying to say here :P
User avatar
Zoxive
Forum Regular
Posts: 974
Joined: Fri Apr 01, 2005 4:37 pm
Location: Bay City, Michigan

Post by Zoxive »

stakes wrote: However this brings me to another question. I'm currently using INT(14) to store timestamps, and so i handle all the required "date-calculations" on the PHP side, is this a generally a "bad way" of doing it? In a performance and efficiency perspective should i rather use the TIMESTAMP for that those fields and do calculations SQL query wise? I hope it makes sense what I'm trying to say here :P
Definitely, then you can scrap this class, and use the built in functions to format Dates.

date_format()

strtotime() date()
User avatar
stakes
Forum Commoner
Posts: 48
Joined: Tue Jun 12, 2007 12:05 pm

Post by stakes »

Oh wow... so making this class was a waste time then hehe. thanks for pointing that out Well at least i learned something during the process. :lol:
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Post by RobertGonzalez »

stakes wrote:Oh wow... so making this class was a waste time then hehe.
If you learned anything about development from it, then no, it was not a waste of time at all.
nickvd
DevNet Resident
Posts: 1027
Joined: Thu Mar 10, 2005 5:27 pm
Location: Southern Ontario
Contact:

Post by nickvd »

Everah wrote:
stakes wrote:Oh wow... so making this class was a waste time then hehe.
If you learned anything about development from it, then no, it was not a waste of time at all.
This has to be Quoted For Truth...

If you learn from anything you do, it was not a waste of time.
Post Reply