Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set a String variable to a Date object in java

Tags:

java

datetime

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.

like image 708
user89910 Avatar asked Dec 01 '22 19:12

user89910


2 Answers

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");
like image 60
AlexR Avatar answered Dec 20 '22 09:12

AlexR


you'll want to use dateformatter

DateFormat formatter = new SimpleDateFormat("MM/dd/yy");
Date date = formatter.parse("01/29/02");
like image 23
75inchpianist Avatar answered Dec 20 '22 10:12

75inchpianist