aspose file tools*
The moose likes Beginning Java and the fly likes convert String to Date Format Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "convert String to Date Format" Watch "convert String to Date Format" New topic
Author

convert String to Date Format

Jayanthi Sampath
Greenhorn

Joined: Jun 26, 2008
Posts: 6
Hi,

I need to convert String("dd-MM-yyyy") format to Date("yyyy-MM-dd")format.


(i.e) String startDate = "23-09-2008" to Date dt = "2008-09-23" as output

Can anyone help me on this?

Thanks
Ola Daniel
Ranch Hand

Joined: Jul 27, 2005
Posts: 105
Google up SimpleDateFormat i.e. java.text.SimpleDateFormat and you will get what you need.


SCJP 1.4, SCWCD 1.4
"Any fool can write code that a computer can understand. Good programmers write code that humans can understand."
- Martin Fowler et al, Refactoring: Improving the Design of Existing Code, 1999
tuty sra
Greenhorn

Joined: Aug 30, 2008
Posts: 16
hi jay,
you can use
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("dd-MM-yyyy");
Date date=simpleDateFormat.parse("23-09-2008");
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 61654
    
  67

Please take the time to choose the correct forum for your posts. This forum is for questions on JSP.

For more information, please read this.

This post has been moved to a more appropriate forum.


[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19761
    
  20

Also note that a Date does not care about formatting. Yes, it does have a toString method, but it uses the system default formatting. Therefore, Date ("yyyy-MM-dd") format means nothing - you have to use another SimpleDateFormat to format the Date object in another String.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18990
    
  40

Originally posted by tuty sra:
hi jay,
you can use
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("dd-MM-yyyy");
Date date=simpleDateFormat.parse("23-09-2008");


And actually, you need to convert twice. First, you need to convert the string to the Date object using the first format. Then you need to convert the Date object back to a string using the second format, so that the string may be printed.

Alternatively, you can just do a string.replaceFirst() call, and bypass the Date object altogether.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: convert String to Date Format