I've a String representing a date.
String date_s = "2011-01-18 00:00:00.0"; I'd like to convert it to a Date and output it in YYYY-MM-DD format.
2011-01-18
How can I achieve this?
Okay, based on the answers I retrieved below, here's something I've tried:
String date_s = " 2011-01-18 00:00:00.0"; SimpleDateFormat dt = new SimpleDateFormat("yyyyy-mm-dd hh:mm:ss"); Date date = dt.parse(date_s); SimpleDateFormat dt1 = new SimpleDateFormat("yyyyy-mm-dd"); System.out.println(dt1.format(date)); But it outputs 02011-00-1 instead of the desired 2011-01-18. What am I doing wrong?
String mydateStr = "/107/2013 12:00:00 AM"; DateFormat df = new SimpleDateFormat("/dMM/yyyy HH:mm:ss aa"); Date mydate = df. parse(mydateStr); Two method above can be used to change a formatted date string from one into the other. See the javadoc for SimpleDateFormat for more info about formatting codes.
String startTime = "08/11/2008 00:00"; // This could be MM/dd/yyyy, you original value is ambiguous SimpleDateFormat input = new SimpleDateFormat("dd/MM/yyyy HH:mm"); Date dateValue = input. parse(startTime); Once you have that done, you can format the dateValue any way you want...
Using java. The LocalDate class represents a date-only value without time-of-day and without time zone. String input = "January 08, 2017"; Locale l = Locale.US ; DateTimeFormatter f = DateTimeFormatter. ofPattern( "MMMM dd, uuuu" , l ); LocalDate ld = LocalDate. parse( input , f );
Use LocalDateTime#parse() (or ZonedDateTime#parse() if the string happens to contain a time zone part) to parse a String in a certain pattern into a LocalDateTime.
String oldstring = "2011-01-18 00:00:00.0"; LocalDateTime datetime = LocalDateTime.parse(oldstring, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S")); Use LocalDateTime#format() (or ZonedDateTime#format()) to format a LocalDateTime into a String in a certain pattern.
String newstring = datetime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")); System.out.println(newstring); // 2011-01-18 Or, when you're not on Java 8 yet, use SimpleDateFormat#parse() to parse a String in a certain pattern into a Date.
String oldstring = "2011-01-18 00:00:00.0"; Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S").parse(oldstring); Use SimpleDateFormat#format() to format a Date into a String in a certain pattern.
String newstring = new SimpleDateFormat("yyyy-MM-dd").format(date); System.out.println(newstring); // 2011-01-18 Update: as per your failed attempt: the patterns are case sensitive. Read the java.text.SimpleDateFormat javadoc what the individual parts stands for. So stands for example M for months and m for minutes. Also, years exist of four digits yyyy, not five yyyyy. Look closer at the code snippets I posted here above.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With