• Post Reply Bookmark Topic Watch Topic
  • New Topic

Date  RSS feed

 
MInu
Ranch Hand
Posts: 517
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,

I need to assign some value to Date,how can i do that?
OR How should i convert or cast a String to Date?

Anybody help me.......
 
Gaurav Chhabras
Ranch Hand
Posts: 126
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
String start = "2004-01-1";
SimpleDateFormat df = new SimpleDateFormat("MM-dd-yyyy");
Date date1 = df.parse(start);
Calendar cal1 = Calendar.getInstance();
cal1.setTime(date1); // At this time your String is converted into Date
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Gaurav's code is not going to work.

Here, you give the variable named 'start' the value '2004-01-1' and then you parse it, but the parser expects the format 'MM-dd-yyyy'. If you try to parse '2004-01-1' using this format, you'll get an exception from the parser.

Anyway, Gaurav's code shows that you can use java.text.SimpleDateFormat to convert strings to Date objects.
 
Stuart Ash
Ranch Hand
Posts: 637
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by minu su:
Hi all,

I need to assign some value to Date,how can i do that?
OR How should i convert or cast a String to Date?

Anybody help me.......


You either do the String-parse way as shown above, or create a Calendar instance, set each element (day, month, etc.) and then get a Date object out of it.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!