Set String variable to Date object in java

I want a String hand to be written as the date for the Date object. I'm trying to say that I want to do 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 a standard date and time, because since I start them from the same machine, the time is taken from the same clock, and every time she gets different times. Therefore, I want to get this time, and also add 1-2 seconds at the end, so that I can test my nodes at different times.

+4
source share
3 answers

Java is a strongly typed language. You cannot assign a date string. However, you can (and should) parse a string into a date. For example, you can use the SimpleDateFormat class as follows:

 SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd"); Date date = fmt.parse("2013-05-06"); 
+7
source
 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); 
+5
source

do you want to use dateformatter

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

Source: https://habr.com/ru/post/1479378/


All Articles