Codessentials

  • Increase font size
  • Default font size
  • Decrease font size
Home Coding tips Java Convert string to date

Convert string to date

The following code shows how we can convert a string representation of date into java.util.Date object.

To convert a string into a date we can use java.text.SimpleDateFormat that extends the java.text.DateFormat abstract class.

 import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.util.Date;

public class StringToDate
{
public static void main(String[] args)
{
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");

try
{
Date today = df.parse("10/12/2008");
System.out.println("Today = " + df.format(today));
} catch (ParseException e)
{
e.printStackTrace();
}
}
}

This is the list of defined patterns that can be used to format the date.

Letter Date / Time Component Examples
G Era designator AD
y Year 1996; 96
M Month in year July; Jul; 07
w Week in year 27
W Week in month 2
D Day in year 189
d Day in month 10
F Day of week in month 2
E Day in week Tuesday; Tue
a Am/pm marker PM
H Hour in day (0-23) 0
k Hour in day (1-24) 24
K Hour in am/pm (0-11) 0
h Hour in am/pm (1-12) 12
m Minute in hour 30
s Second in minute 55
S Millisecond 978
z Time zone Pacific Standard Time; PST; GMT-08:00
Z Time zone -0800
 

Bookmark

AddThis Social Bookmark Button

Related Articles


Newsflash

Jack Wallen is the host of the TechRepublic open source blog as well as a regular writer in the "10 Things..." and the "How Do I..." blogs.

In this article Jack Wallen reviews Yadis! Backup.

Some highlights:

There are tons of backup solutions available, ranging from simple, single-user applications to much larger, complex solutions. Most all of these solutions will do what the creators claim — back up your data. You always hope that data is backed up safely and that it will be there in that unforeseen moment when you need it. There is one backup solution amid the myriad of others that offers a unique little twist on the old tried-and-true process. Yadis! Backup.
...

Yadis! Backup is one of the more foolproof backup solutions I’ve come across. If you are looking for a simple backup solution that does not require any scheduling, this might be what you are seeking. It’s not exactly Enterprise-ready, but for smaller backups it’s a pretty sweet solution.

Read the full article here.