Use java.text.DateFormat and java.text.SimpleDateFormat to do it.
DateFormat sourceFormat = new SimpleDateFormat("dd/MM/yyyy");
String dateAsString = "25/12/2010";
Date date = sourceFormat.parse(dateAsString);
UPDATE:
If you have two Dates hiding in that String, you'll have to break them into two parts. I think others have pointed out the "split" idea. I'd just break at whitespace and throw the "TO" away.
Don't worry about efficiency. Your app is likely to be riddled with inefficiencies much worse than this. Make it work correctly and refactor it only if profiling tells you that this snippet is the worst offender.
Answer from duffymo on Stack OverflowUse java.text.DateFormat and java.text.SimpleDateFormat to do it.
DateFormat sourceFormat = new SimpleDateFormat("dd/MM/yyyy");
String dateAsString = "25/12/2010";
Date date = sourceFormat.parse(dateAsString);
UPDATE:
If you have two Dates hiding in that String, you'll have to break them into two parts. I think others have pointed out the "split" idea. I'd just break at whitespace and throw the "TO" away.
Don't worry about efficiency. Your app is likely to be riddled with inefficiencies much worse than this. Make it work correctly and refactor it only if profiling tells you that this snippet is the worst offender.
tl;dr
LocalDate.parse(
"22/01/2010" ,
DateTimeFormatter.ofPattern( "dd/MM/uuuu" )
)
…more…
// String input is:
// (a) long: "22/01/2010 to 23/01/2010".
// (b) short: "22/01/2010".
// (c) null.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) ;
if( input.length() == 24 ) { // Ex: "22/01/2010 to 23/01/2010"
List<LocalDate> lds = new ArrayList<>( 2 );
String[] inputs = input.split( " to " );
for( String nthInput : inputs ) {
LocalDate ld = LocalDate.parse( nthInput , f ) ;
lds.add( ld );
}
… // Do what you want with `LocalDate` objects collection.
} else if( input.length() == 10 ) { // Ex: "22/01/2010"
LocalDate ld = LocalDate.parse( input , f ) ;
… // Do what you want with `LocalDate` object.
} else if( null == input ) {
… // Decide what you want to do for null input.
} else {
System.out.println( "Unexpected input: " + input ) ;
}
See this code run live at IdeOne.com.
Using java.time
The other Answers use troublesome old date-time classes that are now legacy, supplanted by the java.time classes.
As for handling multiple types of strings, look at the length of the string.
if( input.length() == 10 ) { … }
If long, split on the 4-character substring “ to ”.
String[] inputs = "22/01/2010 to 23/01/2010".split( " to " );
Parse the date string as a LocalDate.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" );
LocalDate ld = LocalDate.parse( "22/01/2010" , f );
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
- Java SE 8, Java SE 9, Java SE 10, and later
- Built-in.
- Part of the standard Java API with a bundled implementation.
- Java 9 adds some minor features and fixes.
- Java SE 6 and Java SE 7
- Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
- Android
- Later versions of Android bundle implementations of the java.time classes.
- For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
Videos
how about this one
try
{
String currentDate = "2014-10-01 00:00:00.0";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
Date tempDate=simpleDateFormat.parse(currentDate);
SimpleDateFormat outputDateFormat = new SimpleDateFormat("dd/MM.YYYY");
System.out.println("Output date is = "+outputDateFormat.format(tempDate));
} catch (ParseException ex)
{
System.out.println("Parse Exception");
}
Use SimpleDateFormat:
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
String date = sdf.format("Your date");
Use this.
java.util.Date date = new Date("Sat Dec 01 00:00:00 GMT 2012");
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String format = formatter.format(date);
System.out.println(format);
you will get the output as
2012-12-01
Modern answer: Use LocalDate from java.time, the modern Java date and time API, and its toString method:
LocalDate date = LocalDate.of(2012, Month.DECEMBER, 1); // get from somewhere
String formattedDate = date.toString();
System.out.println(formattedDate);
This prints
2012-12-01
Some will prefer the more explicit:
String formattedDate = date.format(DateTimeFormatter.ISO_LOCAL_DATE);
ISO in the formatter name refers to the ISO 8601 standard. According to it a date is formatted the way you also want, as yyyy-mm-dd.
A date (whether we’re talking java.util.Date or java.time.LocalDate) doesn’t have a format in it. All it’s got is a toString method that produces some format, and you cannot change the toString method. Fortunately, LocalDate.toString produces exactly the format you asked for.
The Date class is long outdated, and the SimpleDateFormat class that you tried to use, is notoriously troublesome. I recommend you forget about those classes and use java.time instead. The modern API is so much nicer to work with.
Except: it happens that you get a Date from a legacy API that you cannot change or don’t want to change just now. The best thing you can do with it is convert it to java.time.Instant and do any further operations from there:
Date oldfashoinedDate = // get from somewhere
LocalDate date = oldfashoinedDate.toInstant()
.atZone(ZoneId.of("Asia/Beirut"))
.toLocalDate();
Please substitute your desired time zone if it didn’t happen to be Asia/Beirut. Then proceed as above.
Link: Oracle tutorial: Date Time, explaining how to use java.time.
Date is a container for the number of milliseconds since the Unix epoch ( 00:00:00 UTC on 1 January 1970).
It has no concept of format.
Java 8+
LocalDateTime ldt = LocalDateTime.now();
System.out.println(DateTimeFormatter.ofPattern("MM-dd-yyyy", Locale.ENGLISH).format(ldt));
System.out.println(DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.ENGLISH).format(ldt));
System.out.println(ldt);
Outputs...
05-11-2018
2018-05-11
2018-05-11T17:24:42.980
Java 7-
You should be making use of the ThreeTen Backport
Original Answer
For example...
Date myDate = new Date();
System.out.println(myDate);
System.out.println(new SimpleDateFormat("MM-dd-yyyy").format(myDate));
System.out.println(new SimpleDateFormat("yyyy-MM-dd").format(myDate));
System.out.println(myDate);
Outputs...
Wed Aug 28 16:20:39 EST 2013
08-28-2013
2013-08-28
Wed Aug 28 16:20:39 EST 2013
None of the formatting has changed the underlying Date value. This is the purpose of the DateFormatters
Updated with additional example
Just in case the first example didn't make sense...
This example uses two formatters to format the same date. I then use these same formatters to parse the String values back to Dates. The resulting parse does not alter the way Date reports it's value.
Date#toString is just a dump of it's contents. You can't change this, but you can format the Date object any way you like
try {
Date myDate = new Date();
System.out.println(myDate);
SimpleDateFormat mdyFormat = new SimpleDateFormat("MM-dd-yyyy");
SimpleDateFormat dmyFormat = new SimpleDateFormat("yyyy-MM-dd");
// Format the date to Strings
String mdy = mdyFormat.format(myDate);
String dmy = dmyFormat.format(myDate);
// Results...
System.out.println(mdy);
System.out.println(dmy);
// Parse the Strings back to dates
// Note, the formats don't "stick" with the Date value
System.out.println(mdyFormat.parse(mdy));
System.out.println(dmyFormat.parse(dmy));
} catch (ParseException exp) {
exp.printStackTrace();
}
Which outputs...
Wed Aug 28 16:24:54 EST 2013
08-28-2013
2013-08-28
Wed Aug 28 00:00:00 EST 2013
Wed Aug 28 00:00:00 EST 2013
Also, be careful of the format patterns. Take a closer look at SimpleDateFormat to make sure you're not using the wrong patterns ;)
SimpleDateFormat("MM-dd-yyyy");
instead of
SimpleDateFormat("mm-dd-yyyy");
because MM points Month, mm points minutes
SimpleDateFormat sm = new SimpleDateFormat("MM-dd-yyyy");
String strDate = sm.format(myDate);
Use SimpleDateFormat#format(Date):
String start_dt = "2011-01-01";
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date date = (Date)formatter.parse(start_dt);
SimpleDateFormat newFormat = new SimpleDateFormat("MM-dd-yyyy");
String finalString = newFormat.format(date);
String start_dt = "2011-01-31";
DateFormat parser = new SimpleDateFormat("yyyy-MM-dd");
Date date = (Date) parser.parse(start_dt);
DateFormat formatter = new SimpleDateFormat("MM-dd-yyyy");
System.out.println(formatter.format(date));
Prints: 01-31-2011
You have to parse the string to Date then format that Date
String dateStr = "Mon Jan 12 00:00:00 IST 2015";
DateFormat formatter = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy");
DateFormat formatter1 = new SimpleDateFormat("dd.MM.yyyy");
System.out.println(formatter1.format(formatter.parse(dateStr)));
Demo
String dateStr = "Mon Jan 12 00:00:00 IST 2015";
First you have to parse your string to a date:
DateFormat parser = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy");
Date date = parser.parse(dateStr);
and then you can format it:
DateFormat formatter = new SimpleDateFormat("dd.MM.yyyy");
System.out.println(formatter.format(date));