Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

convert String to Date Format

 
Jayanthi Sampath
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 105
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Google up SimpleDateFormat i.e. java.text.SimpleDateFormat and you will get what you need.
 
tuty sra
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 64629
86
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Rob Spoor
Sheriff
Pie
Posts: 20495
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Henry Wong
author
Marshal
Pie
Posts: 20892
75
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic