user89910
user89910

Reputation: 53

Set a String variable to a Date object in java

I want to set a hand written String as the date for a Date object. What I'm trying to say is that I want to do is this:

String date= [date string here!!!];
Date mydate = new Date(date);

Something like that. The reason I want to do this is because I want my network to have standard Date and Time because since I run them from the same machine the time is being taken from the same clock and it gets different time every time. So I want to get that time and also add 1-2 seconds in the end so I can test my nodes with different times.

Upvotes: 4

Views: 67438

Answers (3)

Makky
Makky

Reputation: 17461

String string = "January 2, 2010";
Date date = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH).parse(string);
System.out.println(date); // Sat Jan 02 00:00:00 BOT 2010

updated

String string ="2013-04-26 08:34:55.705"
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").parse(string);
System.out.println(date);

Upvotes: 5

75inchpianist
75inchpianist

Reputation: 4102

you'll want to use dateformatter

DateFormat formatter = new SimpleDateFormat("MM/dd/yy");
Date date = formatter.parse("01/29/02");

Upvotes: 5

AlexR
AlexR

Reputation: 115338

Java is strongly typed language. You cannot assign string to Date. However you can (and should) parse string into date. For example you can use SimpleDateFormat class like the following:

SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
Date date = fmt.parse("2013-05-06");

Upvotes: 8

Related Questions