This blog is meant for my personal reference and keeping track of what I have learnt. Most articles are found through search engines, if you are the author of the article and would like to remove from this blog, please contact me.
Thursday, January 27, 2011
Quickly lock your screen
Quickly lock your screen
by Rob Griffiths, Macworld.com Jan 25, 2006 3:00 am
If you work with any kind of sensitive material—from trade secrets to love letters—you’ve probably wished for a way to block access to your Mac the minute you stand up. There are many ways to do this, from the obvious to the obscure. I’ll cover all the methods I know to accomplish this trick. For most of these methods to work, you need to require a password when your Mac wakes from sleep or screensaver mode. To do this, open System Preferences, go to the Security pane, and select the Require Password to Wake This Computer From Sleep or Screen Saver option. Now you’re ready.
A simple way to protect your files when you walk away from your computer is to hit Shift-Command-Option-Q to do a fast logout of your user. Your Mac will go back to the login screen. However, there’s a huge downside to this method—all of your currently-open documents will close, and any running applications will quit prior to the logout. Clearly there must be better alternatives, and there are.
You could also put the computer to sleep. Go to the Apple menu and select Sleep or, if you’re using a laptop, press the power button and choose Sleep from the pop-up dialog. (Note: This is an edit from the originally posted version, where I said to hold the power button down; if you do that long enough, you’ll turn the computer off.) Of course, it takes a bit of time to put a Mac to sleep and to wake it up. You may also have remote users connected to the machine, or some lengthy program running that you’d rather not interrupt. In those cases, this isn’t the ideal solution.
A relatively quick method of locking your Mac—while still leaving your programs running—is to activate the screen saver using a hot corner . To do this, open the Desktop & Screen Saver System Preferences panel, activate the Screen Saver tab, and click the Hot Corners button. Decide which corner of your screen you’d like to use, then click the corresponding pop-up menu and select Start Screen Saver. Now when it’s time to walk away, just fling your mouse into that corner of the screen, and you’ll trigger the screen saver.
If you have the corners of your screen devoted to Exposé or some other feature, here’s another option. It turns out that the screen saver is just an application, so you can put an alias to it in an easy-to-access location, such as your dock, or the Finder’s sidebar or toolbar. Just navigate to System -> Library -> Frameworks -> Screensaver.framework -> Versions -> A -> Resources, and then drag ScreenSaverEngine.app onto your dock, sidebar, or toolbar. Now when you want the screensaver to activate, just click the convenient icon. The dock will prove the easiest spot to reach, since it’s visible in all applications. If you have a launcher program such as Peter Maurer’s Butler or Objective Development’s LaunchBar, you could even create a keyboard shortcut that will open the program for you, no mousing around required.
Another method of locking your system is to show the login window, without actually logging out. You can do this by enabling fast user switching in the Accounts System Preferences panel. Click the Login Options button (you’ll probably have to enter your administrator password to do this), and then select the Enable Fast User Switching option. Once you have fast user switching enabled, you’ll see either an icon or a name in your menubar, depending on what option you chose on the Login Options screen. Click on your name or icon in the menubar and select Login Window from the drop-down menu. The login window will appear. When you return to your Mac, login as you usually do. All your applications will be just as your left them—even your iTunes music will start up again where it stopped playing, even if that means mid-song.
But what if you don’t want to always lock your screen when the screen saver activates or your computer wakes from sleep? In other words, you don’t want to set that option in the Security pane as you must for the methods I’ve described so far. (After all, it can be a pain to have to enter your password over and over again throughout the day.) Keychain Access holds the key. You can use this application (in your Applications/Utilities folder) to quickly activate your screen saver from the menubar and require a password to turn it off—even if the Security pane option isn’t enabled. Open Keychain Access and then go to Keychain Access: Preferences. Click on the General tab and select the Show Status in Menu Bar option. A small lock icon will appear in your menu bar. Close the Preferences window and quit Keychain Access. Now click the lock icon in your menubar and choose Lock Screen to start your screen saver. You can even define a keyboard shortcut for the Keychain Access Lock Screen menu. First make sure the Lock Screen icon is the leftmost of your Apple-provided menubar icons. Hold down the Command key and drag the lock icon to the left edge of your existing icons, then drop the icon. This step is necessary to make this trick work. Now open System Preferences, and click on the Keyboard & Mouse pane. Click the Keyboard Shortcuts tab, and then click the plus sign to add a shortcut. Leave the pop-up menu set to All Applications, enter Lock Screen for the Menu Title, and then define a keyboard shortcut to use:
Here I’ve defined Shift-Control-F8 as my lock screen shortcut; this may seem an odd combo, but here’s why—since this is a keyboard shortcut for a menubar icon, it only works when that area of the menubar is active (“has focus”). Luckily, one of OS X’s pre-defined keyboard shortcuts is Control-F8, which moves the focus to the status menu area of the menubar, where the lock icon appears. When you hit Control-F8, the leftmost menubar status item will activate; that’s why this trick only works with the lock icon in the leftmost position. And since Control-F8 is the status menu activation key, I assigned a very similar keystroke for the Lock Screen function. So to lock the screen, hit Control-F8, and then Shift-Control-F8. Presto, the screen saver will activate! Note that this may not work for everyone, depending on what other menu extras you have installed. You should always be able to hit Control-F8 and use the arrow keys, however, which is almost as easy and still mouse-less.
I’m sure I’ve missed at least a few additional methods of quickly locking your screen; if you have one, please share it in the comments.
Tuesday, January 25, 2011
A Rails Feature You Should be Using: with_scope
A Rails Feature You Should be Using: with_scope
Posted by ryan at 5:48 AM on Thursday, July 20, 2006
The with_scope method provided by ActiveRecord has been talked about before (see the resources section below), but I don’t feel like people recognize what a great utility it is. Maybe awareness will increase with more tools that make use of this feature, like the MeantimeFilter by Roman, or just more public conversation about it. Add the following to the latter category:
with_scope lets you bind a block of code operating on an active record model to a particular subset of that model’s collection. For instance, using the standard blog application example, if I have a controller method that performs a series of operations on a single user’s articles I would need to pass in the user id condition on every operation:
def create_avoid_dups
user_id = current_user.id
# Find all user's posts
user_posts = Post.find(:all, :conditions => ["user_id = ?", user_id])
# Do some logic looking for dups in user_posts
...
# then create new
@post = Post.create(:body => params[:body], :user_id => user_id)
end
Notice we had to pass in the user_id on both the find and create method. with_scope lets us extract that parameter so the core operations aren’t obscured by excessive parameters:
def create_avoid_dups
Post.with_scope(:find => {:conditions => "user_id = #{current_user.id}"},
:create => {:user_id => current_user.id}) do
# Find all user's posts
# No longer need user_id condition since we're in scope
user_posts = Post.find(:all)
# Do some logic looking for dups in user_posts
...
# then create new without specifying user_id
@post = Post.create(:body => params[:body])
@post.user_id #=> user_id
end
end
with_scope allowed us to specify conditions of the Post that would apply throughout the course of the block (conditions specified by operation, in this case :find and :create)
Contrived examples such as this one don’t do a great job of showcasing how useful this method is – but imagine never having to specify the user_id in any controller method because it’s been automatically scoped to that user for you. That’s exactly what the previously mentioned meantime filter does.
So don’t be shy. If you find yourself writing code that applies to a known subset of items, scope it with with_scope. All the cool kids are doing it.
Posted by ryan at 5:48 AM on Thursday, July 20, 2006
The with_scope method provided by ActiveRecord has been talked about before (see the resources section below), but I don’t feel like people recognize what a great utility it is. Maybe awareness will increase with more tools that make use of this feature, like the MeantimeFilter by Roman, or just more public conversation about it. Add the following to the latter category:
with_scope lets you bind a block of code operating on an active record model to a particular subset of that model’s collection. For instance, using the standard blog application example, if I have a controller method that performs a series of operations on a single user’s articles I would need to pass in the user id condition on every operation:
def create_avoid_dups
user_id = current_user.id
# Find all user's posts
user_posts = Post.find(:all, :conditions => ["user_id = ?", user_id])
# Do some logic looking for dups in user_posts
...
# then create new
@post = Post.create(:body => params[:body], :user_id => user_id)
end
Notice we had to pass in the user_id on both the find and create method. with_scope lets us extract that parameter so the core operations aren’t obscured by excessive parameters:
def create_avoid_dups
Post.with_scope(:find => {:conditions => "user_id = #{current_user.id}"},
:create => {:user_id => current_user.id}) do
# Find all user's posts
# No longer need user_id condition since we're in scope
user_posts = Post.find(:all)
# Do some logic looking for dups in user_posts
...
# then create new without specifying user_id
@post = Post.create(:body => params[:body])
@post.user_id #=> user_id
end
end
with_scope allowed us to specify conditions of the Post that would apply throughout the course of the block (conditions specified by operation, in this case :find and :create)
Contrived examples such as this one don’t do a great job of showcasing how useful this method is – but imagine never having to specify the user_id in any controller method because it’s been automatically scoped to that user for you. That’s exactly what the previously mentioned meantime filter does.
So don’t be shy. If you find yourself writing code that applies to a known subset of items, scope it with with_scope. All the cool kids are doing it.
JavaScript Testing with Cucumber and Capybara
(ref: http://openmonkey.com/articles/2010/04/javascript-testing-with-cucumber-capybara)
JavaScript Testing with Cucumber and Capybara
Tim Riley 2010.04.09
Capybara is a Ruby DSL for easily writing integration tests for Rack applications. It is an alternative to Webrat and can easily replace it as a backend for your Cucumber features. Its power and utility lies in that it comes bundled with several different browser simulators, equipping you with a flexible toolkit for testing all parts of your application, from the simplest page to the most complex, JavaScript-heavy page.
JavaScript Testing with Cucumber and Capybara
Tim Riley 2010.04.09
Capybara is a Ruby DSL for easily writing integration tests for Rack applications. It is an alternative to Webrat and can easily replace it as a backend for your Cucumber features. Its power and utility lies in that it comes bundled with several different browser simulators, equipping you with a flexible toolkit for testing all parts of your application, from the simplest page to the most complex, JavaScript-heavy page.
Cucumber Tutorial - Tagging
After a few months, scenarios and features in a project can become unwieldy. With hundreds of feature files, we might not want to run everything all the time. Even without that, it is often useful to be able to check just a subset of the features, for example skip running one or two very slow tests to get faster feedback.
Cucumber allows us to manage large groups of scenarios easier with tags. Tags are free-form text comments assigned to a scenario, that provide meta-data about the type, nature or group of that scenario. You can assign tags to a scenario by putting it before the scenario header, adding an ‘at’ sign (@) before the tag name.
For example:
For example:
@slowtest
Scenario: end-to-end signup
...
You can execute only the scenarios with a particular tag using the --tags option, for example:
cucumber --tags @fasttest
Another option is to skip only the scenarios without a particular tag. For
that, prefix the tag with a tilde (~). Here is an example:
cucumber --tags ~@slowtest
Wednesday, January 19, 2011
Rails installation
install specific version of rails
sudo gem install -v=2.2.2 rails --include-dependencies
Installing Ruby on Rails on Mac OS X
Installing Ruby on Rails on Mac OS X
Leopard (10.5)
Ruby (1.8.6), Ruby Gems (1.0.1) and Rails (1.2.3) ship with the latest version of OS X (10.5, Leopard).
You may want to upgrade Rails to take advantage of the latest and greatest improvements. The version of Rails that ships with OS X is rather old (in Rails development terms).
You should also make sure you have xCode tools installed from your OSX disk, since you will likely run into the need to compile applications during your run with Rails.
To accomplish this, you should first update Ruby Gems.
$ sudo gem install rubygems-update $ sudo update_rubygems
Then a simple re-installation of Rails will get you to the latest release.
$ sudo gem update $ sudo gem update --system $ sudo gem install rails
Tiger (10.4) and Panther (10.3)
RubyOSX v1.2 is a one click installer that will install Ruby 1.8.6, RubyGems 0.9.4, Mongrel 1.0.1 and SQLite 3.4.0. for Tiger (10.4) and Panther (10.3). It however, will not install Rails. After installing RubyOSX you should first update Ruby Gems.
$ sudo gem install rubygems-update $ sudo update_rubygems
Then a simple installation of Rails will get you to the latest release.
$ sudo gem install rails
Alternative Method for Leopard (10.5) and Tiger (10.4)
Bitnami RubyStack
Using Bitnami RubyStack with FiveRuns TuneUp BitNami RubyStack (1.4-beta-1) ships with the following:
- Ruby 1.8.6 and 1.9.0 developer branch
- RubyGems 1.2.0
- Rails 2.1.1
- ImageMagick 6.3.6
- Subversion 1.4.6
- SQLite 3.5.1
- MySQL 5.0.51a
- Apache 2.2.8
- Mongrel Web Server 1.1.5
- Capistrano 2.5
- PHP 5.2.6
- phpMyAdmin 2.11.2.2
- Git 1.5.5
- Nginx 0.6.30
Note: Bitnami RubyStack will not support Passenger, as it does not support Windows platform
If you select Developer version then you will get a choice of installing PhpMyAdmin. In developer version Apache isn't preconfigured 
If you select Production version then Bitnami will install Mongrel Cluster, with Apache preconfigured to act as a load balancer for Mongrel

Bitnami will install 3 databases, Developer, Production and Test databases. Here you should add a user that will have rights to these databases.

All Done.
Macports
You may wish to use MacPorts to install Rails if you are using Leopard (10.5), Tiger (10.4) or Panther (10.3).
First you should Download the latest version of Xcode Tools if you have the currently shipping release of Mac OS X. Without Xcode Macports will not work
Download and install the appropriate version of Macports from MacPorts install page. MacPorts can be installed with a .dmg image using a familiar step-by-step installer. This will take quite some time to install, so be patient, it downloads the entire ports repository during “Finishing Installation” phase.
Command Line option
Open the Terminal application and type the following command, followed by the return key. It will most likely prompt you to enter your password.
$ sudo port install rb-rails
or type in the complete path like so
$ sudo /opt/local/bin/port install rb-rails
This will install the required rails dependencies like Ruby, RubyGems, Rake and SQLite. This will also take a very long time, depending on your computer speed, since everything is compiled from source.
That's it! Now you're ready to create new Rails applications.
If you want you can also install Mongrel, Capistrano, Mysql and Rspec using the following command.
$ sudo port install rb-capistrano rb-mongrel_cluster rb-mysql rb-rspec-rails
GUI option
Install Porticus, which is a gui for Macports Package Manager. Search for rails in the search bar in the top right corner 
Select rb-rails and click the install icon on the top right corner. It will install all the required dependencies. All done, rails is now installed. If you want you can also install rb-mongrel_cluster. Although its recommended to use Passenger with apache.
( http://wiki.rubyonrails.org/getting-started/installation/mac)
Thursday, December 2, 2010
How do I... Perform date/time arithmetic with Java's Calendar class?
(from http://blogs.techrepublic.com.com/howdoi/?p=116)
Java’s Calendar class offers a set of methods for converting and manipulating temporal information. In addition to retrieving the current date and time, the Calendar class also provides an API for date arithmetic. The API takes care of the numerous minor adjustments that have to be made when adding and subtracting intervals to date and time values.
Calendar’s built-in date/time arithmetic API is extremely useful. For example, consider the number of lines of code that go into calculating what the date will be five months from today. Try doing this yourself — you need to know the number of days in the current month and in the intervening months, as well as make end-of-year and leap year modifications to arrive at an accurate final result. These kinds of calculations are fairly complex and are quite easy to get wrong — especially if you’re a novice developer.
This tutorial examines the Calendar class API and presents examples of how you can use Calendar objects to add and subtract time spans to and from dates and times, as well as how to evaluate whether one date precedes or follows another.
Adding time spans
Let’s say you want to add a time span to a starting date and print the result. Consider the following example, which initializes a Calendar to 01 Jan 2007 and then adds two months and one day to it to obtain a new value:
package datetime;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
public class myClass
{
public static void main(String[] args)
{
myClass tdt = new myClass();
tdt.doMath();
}
/**
* method to create a calendar object, add 2m 1d, and print result
*/
private void doMath()
{
// set calendar to 1 Jan 2007
Calendar calendar = new GregorianCalendar(2007,Calendar.JANUARY,1);
System.out.println("Starting date is: ");
printCalendar(calendar);
// add 2m 1d
System.out.println("Adding 2m 1d... ");
calendar.add(Calendar.MONTH,2);
calendar.add(Calendar.DAY_OF_MONTH,1);
// print ending date value
System.out.println("Ending date is: ");
PrintCalendar(calendar);
}
/**
* utility method to print a Calendar object using SimpleDateFormat.
* @param calendar calendar object to be printed.
*/
private void printCalendar(Calendar calendar)
{
// define output format and print
SimpleDateFormat sdf = new SimpleDateFormat("d MMM yyyy hh:mm aaa");
String date = sdf.format(calendar.getTime());
System.out.println(date);
}
}The main workhorse of this class is the doMath() method, which begins by initializing a new GregorianCalendar object to 1 Jan 2007. Next, the object’s add() method is invoked; this method accepts two arguments: the name of the field to add the value to and the amount of time to be added. In this example, the add() method is called twice — first to add two months to the starting date and then to add a further one day to the result. Once the addition is performed, the printCalendar() utility method is used to print the final result. Notice the use of the SimpleDateFormat object to turn the output of getTime() into a human-readable string.
When you run the class, this is the output you’ll see:
Starting date is: 1 Jan 2007 12:00 AM Adding 2m 1d... Ending date is: 2 Mar 2007 12:00 AM
This kind of addition also works with time values. To illustrate, consider the next example, which adds 14 hours and 55 minutes to a starting time value:
package datetime;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
public class myClass
{
public static void main(String[] args)
{
myClass tdt = new myClass();
tdt.doMath();
}
/**
* method to create a calendar object, add 14h 55min, and print result
*/
private void doMath()
{
// set calendar to 1 Jan 2007
Calendar calendar = new GregorianCalendar(2007,Calendar.JANUARY,1, 1,0);
System.out.println("Starting date is: ");
printCalendar(calendar);
// add 14h 55min
System.out.println("Adding 14h 55min... ");
calendar.add(Calendar.HOUR,14);
calendar.add(Calendar.MINUTE,55);
// print final value
System.out.println("Ending date is: ");
printCalendar(calendar);
}
/**
* utility method to print a Calendar object using SimpleDateFormat.
* @param calendar calendar object to be printed.
*/
private void printCalendar(Calendar calendar)
{
// define output format and print
SimpleDateFormat sdf = new SimpleDateFormat("d MMM yyyy hh:mm aaa");
String date = sdf.format(calendar.getTime());
System.out.println(date);
}
}This is almost identical to the previous class except that the calls to add() involve the calendar’s hour and minute fields. Here’s the output:
Starting date is:
1 Jan 2007 01:00 AM
Adding 14h 55min…
Ending date is:
1 Jan 2007 03:55 PM
1 Jan 2007 01:00 AM
Adding 14h 55min…
Ending date is:
1 Jan 2007 03:55 PM
Tip: You can obtain a complete list of the calendar constants that can be used with add() from the Calendar class’ documentation.
Subtracting time spans
Subtraction is fairly easy as well — you simply use negative values as the second argument to add(). Here’s an example:
package datetime;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
public class myClass
{
public static void main(String[] args)
{
myClass tdt = new myClass();
tdt.doMath();
}
/**
* method to create a calendar object, subtract time, and print result
*/
private void doMath()
{
// initialize calendar
Calendar calendar = new GregorianCalendar(2007,Calendar.JANUARY,2, 3,30);
System.out.println("Starting date is: ");
printCalendar(calendar);
// subtract 1y 1d 4h 5min
System.out.println("Subtracting 1y 1d 4h 5min... ");
calendar.add(Calendar.YEAR,-1);
calendar.add(Calendar.DAY_OF_MONTH,-1);
calendar.add(Calendar.HOUR,-4);
calendar.add(Calendar.MINUTE,-5);
// print result
System.out.println("Ending date is ");
printCalendar(calendar);
}
/**
* utility method to print a Calendar object using SimpleDateFormat.
* @param calendar calendar object to be printed.
*/
private void printCalendar(Calendar calendar)
{
// define output format and print
SimpleDateFormat sdf = new SimpleDateFormat("d MMM yyyy hh:mm aaa");
String date = sdf.format(calendar.getTime());
System.out.println(date);
}
}Here’s the output:
Starting date is: 2 Jan 2007 03:30 AM Subtracting 1y 1d 4h 5min... Ending date is 31 Dec 2005 11:25 PM
In this example, the Calendar object automatically takes care of adjusting the year and the day when the subtraction results in the date “overflowing” from 1 Jan 2006 to 31 Dec 2005.
Adding vs. rolling
As the previous example illustrates, the add() method automatically takes care of rolling over days, months, and years when a particular calendar field “overflows” as a result of addition or subtraction. However, this behavior is often not what you want. In those situations, the Calendar object also has a roll() method, which avoids incrementing or decrementing larger calendar fields when such overflow occurs. To see how this works, look at the following example:
package datetime;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
public class myClass
{
public static void main(String[] args)
{
myClass tdt = new myClass();
tdt.doAdd();
tdt.doRoll();
}
/**
* method to create a calendar object, add 1m, and print result
*/
private void doAdd()
{
// initialize calendar
Calendar calendar = new GregorianCalendar(2006, Calendar.DECEMBER,1);
System.out.println("Starting date is: ");
printCalendar(calendar);
System.out.println("After add()ing 1 month, ending date is: ");
calendar.add(Calendar.MONTH, 1);
printCalendar(calendar);
}
/**
* method to create a calendar object, roll 1m, and print result
*/
private void doRoll()
{
// initialize calendar
Calendar calendar = new GregorianCalendar(2006, Calendar.DECEMBER,1);
System.out.println("Starting date is: ");
printCalendar(calendar);
System.out.println("After roll()ing 1 month, ending date is: ");
calendar.roll(Calendar.MONTH, 1);
printCalendar(calendar);
}
/**
* utility method to print a Calendar object using SimpleDateFormat.
* @param calendar calendar object to be printed.
*/
private void printCalendar(Calendar calendar)
{
// define output format and print
SimpleDateFormat sdf = new SimpleDateFormat("d MMM yyyy hh:mm aaa");
String date = sdf.format(calendar.getTime());
System.out.println(date);
}
}Here’s the output:
Starting date is: 1 Dec 2006 12:00 AM After add()ing 1 month, ending date is: 1 Jan 2007 12:00 AM Starting date is: 1 Dec 2006 12:00 AM After roll()ing 1 month, ending date is: 1 Jan 2006 12:00 AM
In the first case, when one month is added to the starting date of 1 Dec 2006, the add() method realizes that a year change will occur as a result of the addition, and the year is rolled over to 2007. When using roll(), this behavior is disabled, and only the month field is incremented by 1, with the year change ignored. Depending on the requirements of your application, you may find such restricted changes useful in certain situations.
Checking date precedence
The Calendar object also includes the compareTo() method, which lets you compare two dates to find out which one comes earlier. The compareTo() method accepts another Calendar object as an input argument and returns a value less than zero if the following conditions are true:
- The date and time of the input Calendar object is later than that of the calling Calendar object.
- A value greater than zero if the reverse is true.
- A value of 0 if the two Calendar objects represent the same date.
Here’s an example that compares 1 Jan 2007 12:00 AM and 1 Jan 2007 12:01 AM with compareTo():
package datetime;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
public class myClass
{
public static void main(String[] args)
{
// initialize two calendars
Calendar calendar1 = new GregorianCalendar(2007,Calendar.JANUARY,1,0,0,0);
Calendar calendar2 = new GregorianCalendar(2007,Calendar.JANUARY,1,0,1,0);
// define date format
String date1 = null;
String date2 = null;
SimpleDateFormat sdf = new SimpleDateFormat("d MMM yyyy hh:mm aaa");
// compare dates
if((calendar1.compareTo(calendar2)) < 0)
{
date1 = sdf.format(calendar1.getTime());
date2 = sdf.format(calendar2.getTime());
}
else
{
date1 = sdf.format(calendar2.getTime());
date2 = sdf.format(calendar1.getTime());
}
System.out.println(date1 + " occurs before " + date2);
System.out.println(date2 + " occurs after " + date1);
}
}Here’s the output:
1 Jan 2007 12:00 AM occurs before 1 Jan 2007 12:01 AM 1 Jan 2007 12:01 AM occurs after 1 Jan 2007 12:00 AM
This example uses two Calendar objects and a little date arithmetic:
package datetime;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
public class myClass
{
public static void main(String[] args)
{
// initialize two calendars
Calendar calendar1 = new GregorianCalendar(2007,Calendar.FEBRUARY,16,0,0,0);
Calendar calendar2 = new GregorianCalendar(2007,Calendar.FEBRUARY,18,0,1,0);
// define date format
SimpleDateFormat sdf = new SimpleDateFormat("d MMM yyyy hh:mm aaa");
// add 2d to calendar #1
calendar1.add(Calendar.DAY_OF_MONTH, 2);
// subtract 1min from calendar #2
calendar2.add(Calendar.MINUTE, -1);
// compare dates
String date1 = sdf.format(calendar1.getTime());
String date2 = sdf.format(calendar2.getTime());
if((calendar1.compareTo(calendar2)) < 0)
{
System.out.println(date1 + " occurs before " + date2);
}
else if((calendar1.compareTo(calendar2)) > 0)
{
System.out.println(date1 + " occurs after " + date2);
}
else
{
System.out.println("The two dates are identical: " + date1);
}
}
}Although both calendars start out differently, they’re converted to the same time stamp through a bit of date arithmetic. This is verified via the compareTo() method, which returns 0 when asked to compare them, indicating that they represent the same instant in time:
The two dates are identical: 18 Feb 2007 12:00 AM
Imagine the possibilities
The Calendar class’ date/time API is a nifty tool for accurately manipulating date and time values without too much stress or custom coding. The examples in this article are just some of many possibilities this API opens up — the rest is up to your imagination.
——————————————————————————–
Get Java tips in your inboxDelivered each Thursday, our free Java newsletter provides insight and hands-on tips you need to unlock the full potential of this programming language. Automatically subscribe today!
Get IT tips, news, and reviews delivered directly to your inbox by subscribing toTechRepublic's free newsletters.
Subscribe to:
Posts (Atom)