Hi i want to convert the current date to this format YYYY-MM-DD. However, it will convert the date into String format, but i want to convert it back into Date format. So can anyone advise on this?
This is my code so far
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date();
String datestring = dateFormat.format(date);
try this:
String DATE_FORMAT_NOW = "yyyy-MM-dd";
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
String stringDate = sdf.format(date );
try {
Date date2 = sdf.parse(stringDate);
} catch(ParseException e){
//Exception handling
} catch(Exception e){
//handle exception
}
Use DateFormat#parse(String):
Date date = dateFormat.parse("2013-10-22");
tl;dr
How to convert date to string and to date again?
LocalDate.now().toString()
2017-01-23
…and…
LocalDate.parse( "2017-01-23" )
java.time
The Question uses troublesome old date-time classes bundled with the earliest versions of Java. Those classes are now legacy, supplanted by the java.time classes built into Java 8, Java 9, and later.
Determining today’s date requires a time zone. For any given moment the date varies around the globe by zone.
If not supplied by you, your JVM’s current default time zone is applied. That default can change at any moment during runtime, and so is unreliable. I suggest you always specify your desired/expected time zone.
ZoneId z = ZoneId.of( "America/Montreal" ) ;
LocalDate ld = LocalDate.now( z ) ;
ISO 8601
Your desired format of YYYY-MM-DD happens to comply with the ISO 8601 standard.
That standard happens to be used by default by the java.time classes when parsing/generating strings. So you can simply call LocalDate::parse and LocalDate::toString without specifying a formatting pattern.
String s = ld.toString() ;
To parse:
LocalDate ld = LocalDate.parse( s ) ;
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.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, 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
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
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.
try this function
public static Date StringToDate(String strDate) throws ModuleException {
Date dtReturn = null;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-mm-dd");
try {
dtReturn = simpleDateFormat.parse(strDate);
} catch (ParseException e) {
e.printStackTrace();
}
return dtReturn;
}
Convert Date to String using this function
public String convertDateToString(Date date, String format) {
String dateStr = null;
DateFormat df = new SimpleDateFormat(format);
try {
dateStr = df.format(date);
} catch (Exception ex) {
System.out.println(ex);
}
return dateStr;
}
From Convert Date to String in Java
. And convert string to date again
public Date convertStringToDate(String dateStr, String format) {
Date date = null;
DateFormat df = new SimpleDateFormat(format);
try {
date = df.parse(dateStr);
} catch (Exception ex) {
System.out.println(ex);
}
return date;
}
From Convert String to date in Java
Related
I am working on android project and i receive from API the time in format like this "10:12:57 am" (12 hour format) and I want to display it in format "10:12" just like this (on a 24 hour clock). How to reformat that time?
So 12:42:41 am should become 00:42. And 02:13:39 pm should be presented as 14:13.
Using java.time (Modern Approach)
String str = "10:12:57 pm";
DateTimeFormatter formatter_from = DateTimeFormatter.ofPattern( "hh:mm:ss a", Locale.US ); //Use pattern symbol "hh" for 12 hour clock
LocalTime localTime = LocalTime.parse(str.toUpperCase(), formatter_from );
DateTimeFormatter formatter_to = DateTimeFormatter.ofPattern( "HH:mm" , Locale.US ); // "HH" stands for 24 hour clock
System.out.println(localTime.format(formatter_to));
See BasilBourque answer below and OleV.V. answer here for better explanation.
Using SimpleDateFormat
String str = "10:12:57 pm";
SimpleDateFormat formatter_from = new SimpleDateFormat("hh:mm:ss a", Locale.US);
//Locale is optional. You might want to add it to avoid any cultural differences.
SimpleDateFormat formatter_to = new SimpleDateFormat("HH:mm", Locale.US);
try {
Date d = formatter_from.parse(str);
System.out.println(formatter_to.format(d));
} catch (ParseException e) {
e.printStackTrace();
}
If your input is 10:12:57 am, output will be 10:12. And if string is 10:12:57 pm, output will be 22:12.
tl;dr
LocalTime // Represent a time-of-day, without a date and without a time zone.
.parse( // Parse an input string to be a `LocalTime` object.
"10:12:57 am".toUpperCase() , // The cultural norm in the United States expects the am/pm to be in all-uppercase. So we convert our input value to uppercase.
DateTimeFormatter.ofPattern( "hh:mm:ss a" , Locale.US ) // Specify a formatting pattern to match the input.
) // Returns a `LocalTime` object.
.format( // Generate text representing the value in this date-time object.
DateTimeFormatter.ofPattern( "HH:mm" , Locale.US ) // Note that `HH` in uppercase means 24-hour clock, not 12-hour.
) // Returns a `String`.
10:12
java.time
The modern approach uses the java.time classes that years ago supplanted the terrible Date & Calendar & SimpleDateFormat classes.
The LocalTime class represents a time-of-day in a generic 24-hour day, without a date and without a time zone.
Parse your string input as a LocalTime object.
String input = ( "10:12:57 am" );
DateTimeFormatter fInput = DateTimeFormatter.ofPattern( "HH:mm:ss a" , Locale.US );
LocalTime lt = LocalTime.parse( input.toUpperCase() , fInput ); // At least in the US locale, the am/pm is expected to be in all uppercase: AM/PM. So we call `toUppercase` to convert input accordingly.
lt.toString(): 10:12:57
Generate a String with text in the hour-minute format you desire. Note that HH in uppercase means 24-hour clock.
DateTimeFormatter fOutput = DateTimeFormatter.ofPattern( "HH:mm" , Locale.US );
String output = lt.format( fOutput );
output: 10:12
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, Java SE 11, and later - 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
Most 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.
Try this:
SimpleDateFormat displayFormat = new SimpleDateFormat("HH:mm");
SimpleDateFormat parseFormat = new SimpleDateFormat("hh:mm:ss a");
try {
Date date = parseFormat.parse("10:12:57 pm");
System.out.println(parseFormat.format(date) + " = " + displayFormat.format(date));
}
catch (Exception e) {
e.printStackTrace();
}
The gives:
10:12:57 pm = 22:12
You can use such formatters:
SimpleDateFormat formatterFrom = new SimpleDateFormat("hh:mm:ss aa");
SimpleDateFormat formatterTo = new SimpleDateFormat("HH:mm");
Date date = formatterFrom.parse("10:12:57 pm");
System.out.println(formatterTo.format(date));
String str ="10:12:57 pm";
SimpleDateFormat formatter_from = new SimpleDateFormat("hh:mm:ss aa", Locale.US);
SimpleDateFormat formatter_to = new SimpleDateFormat("HH:mm",Locale.US);
try {
Date d = formatter_from.parse(str);
System.out.println(formatter_to.format(d));
} catch (ParseException e) {
e.printStackTrace();
}
Im trying to save two dates into a serialized . bin file. I use the Calendar class to get the current date then I add 30 days onto it. So I try to save two date variables fd (First Date) and ed (Expiration Date). If I change them to Strings in the expiration_date_serial file they work, but when I try to save them as Date they throw errors on these 2 lines:
exp_date.fd = current_formateddate;
exp_date.ed = formateddate;
Error:
incompatible types: java.lang.String cannot be converted to java.util.Date
Runnable Class:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class GetCurrentDate {
public static void main(String[] args) {
// get current date
DateFormat currentdateFormat = new SimpleDateFormat("MM/dd/yy");
Date current_date = new Date();
String current_formateddate = currentdateFormat.format(current_date);
System.out.println("Current date: " + (current_formateddate));
// ADD 30 days to the current date
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yy");
Calendar c = Calendar.getInstance();
c.add(Calendar.DATE, 30);
Date d = c.getTime();
String formateddate = dateFormat.format(d);
System.out.println("+ 30 days: " + formateddate);
// Serialization start
expiration_date_serial exp_date = new expiration_date_serial();
exp_date.fd = current_formateddate;
exp_date.ed = formateddate;
String fileName = "data.bin";
try {
ObjectOutputStream os = new ObjectOutputStream(
new FileOutputStream(fileName));
os.writeObject(exp_date);
os.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Done writing...");
try {
ObjectInputStream is = new ObjectInputStream(new FileInputStream(
fileName));
expiration_date_serial p = (expiration_date_serial) is.readObject();
System.out.println("First Date = " + p.fd +
" Expiration Date = " + p.ed);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Other class:
import java.io.Serializable;
import java.util.Date;
public class expiration_date_serial implements Serializable {
public Date fd;//First Date
public Date ed;//Expiration Date
}
In Java, you cannot assign a value of type String to a field of type Date, that's why the error. It happens even before the serialization.
Your most obvious options are:
change a type of the field to String
don't convert Date objects to String and save them as is
You should decide what suits your needs better.
tl;dr
LocalDate.now( ZoneId.of( "America/Montreal" ) )
.plusDays( 30 )
.toString()
Details
The Answer by Orlangure is correct, about assigning across types.
Also, other problems include:
Using old outmoded legacy classes for date-time handling.
Poor choice of format for serialized date values.
Incorrectly choosing to use a date-time class for a date-only value.
java.time
The old date-time classes are poorly-designed, confusing, and troublesome. Avoid them. Now legacy, supplanted by the java.time classes.
ISO 8601
The ISO 8601 standard defines textual formats for date-time values. These formats are unambiguous, intuitive across cultures, and practical. The standard format for a date-only value is YYYY-MM-DD such as 2016-10-23.
The java.time classes use ISO 8601 by default when parsing and generating Strings to represent their date-time values.
LocalDate
The LocalDate class represents a date-only value without time-of-day and without time zone.
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );
Strings
To generate an ISO 8601 compliant String, simply call toString.
String output = today.toString(); // 2016-10-23
To parse, simply call parse.
LocalDate ld = LocalDate.parse( "2016-10-23" );
Date math
You can add or subtract amounts of time. Just call the plus… and minus… methods.
LocalDate thirtyDaysAgo = ld.minusDays( 30 );
LocalDate oneMonthAgo = ld.minusMonths( 1 );
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 java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8 and SE 9 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 SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use….
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.
I have a SimleDateFormat like this
SimpleDateFormat format = new SimpleDateFormat("MMM dd,yyyy hh:mm");
String date = format.format(Date.parse(payback.creationDate.date));
I'm giving date with the format like "Jan,23,2014".
Now, I want to get day, month and year separately. How can I implement this?
If you need to get the values separately, then use more than one SimpleDateFormat.
SimpleDateFormat dayFormat = new SimpleDateFormat("dd");
String day = dayFormat.format(Date.parse(payback.creationDate.date));
SimpleDateFormat monthFormat = new SimpleDateFormat("MM");
String month = monthFormat .format(Date.parse(payback.creationDate.date));
etc.
SimpleDateFormat format = new SimpleDateFormat("MMM dd,yyyy hh:mm", Locale.ENGLISH);
Date theDate = format.parse("JAN 13,2014 09:15");
Calendar myCal = new GregorianCalendar();
myCal.setTime(theDate);
System.out.println("Day: " + myCal.get(Calendar.DAY_OF_MONTH));
System.out.println("Month: " + myCal.get(Calendar.MONTH) + 1);
System.out.println("Year: " + myCal.get(Calendar.YEAR));
Wow, SimpleDateFormat for getting string parts? It can be solved much easier if your input string is like "Jan,23,2014":
String input = "Jan,23,2014";
String[] out = input.split(",");
System.out.println("Year = " + out[2]);
System.out.println("Month = " + out[0]);
System.out.println("Day = " + out[1]);
Output:
Year = 2014
Month = Jan
Day = 23
But if you really want to use SimpleDateFormat because of some reason, the solution will be the following:
String input = "Jan,23,2014";
SimpleDateFormat format = new SimpleDateFormat("MMM,dd,yyyy");
Date date = format.parse(input);
Calendar calendar = Calendar.getInstance(TimeZone.getDefault());
calendar.setTime(date);
System.out.println(calendar.get(Calendar.YEAR));
System.out.println(calendar.get(Calendar.DAY_OF_MONTH));
System.out.println(new SimpleDateFormat("MMM").format(calendar.getTime()));
Output:
2014
23
Jan
The accepted answer here suggests to use more than one SimpleDateFormat, but it's possible to do this using one SimpleDateFormat instance and calling applyPattern.
Note: I believe this post would also be helpful for those who were searching for setPattern() just like me.
Date date=new Date();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat();
simpleDateFormat.applyPattern("dd");
System.out.println("Day : " + simpleDateFormat.format(date));
simpleDateFormat.applyPattern("MMM");
System.out.println("Month : " + simpleDateFormat.format(date));
simpleDateFormat.applyPattern("yyyy");
System.out.println("Year : " + simpleDateFormat.format(date));
tl;dr
Use LocalDate class.
LocalDate
.parse(
"Jan,23,2014" ,
DateTimeFormatter.ofPattern( "MMM,dd,uuuu" , Locale.US )
)
.getYear()
… or .getMonthValue() or .getDayOfMonth.
java.time
The other Answers use outmoded classes. The java.time classes supplant those troublesome old legacy classes.
LocalDate
The LocalDate class represents a date-only value without time-of-day and without time zone.
String input = "Jan,23,2014";
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MMM,d,uuuu" );
LocalDate ld = LocalDate.parse( input , f );
Interrogate for the parts you want.
int year = ld.getYear();
int month = ld.getMonthValue();
int dayOfMonth = ld.getDayOfMonth();
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, Java SE 11, and later - 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
Most 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.
Use this to parse "Jan,23,2014"
SimpleDateFormat fmt = new SimpleDateFormat("MMM','dd','yyyy");
Date dt = fmt.parse("Jan,23,2014");
then you can get whatever part of the date.
Are you accepting this ?
int day = 25 ; //25
int month =12; //12
int year = 1988; // 1988
Calendar c = Calendar.getInstance();
c.set(year, month-1, day, 0, 0);
SimpleDateFormat format = new SimpleDateFormat("MMM dd,yyyy hh:mm");
System.out.println(format.format(c.getTime()));
Display as Dec 25,1988 12:00
UPDATE : based on Comment
DateFormat format = new SimpleDateFormat("MMM");
System.out.println(format.format(format.parse("Jan,23,2014")));
NOTE: Date.parse() is #deprecated and as per API it is recommend to use DateFormat.parse
public static String getDate(long milliSeconds, String dateFormat) {
// Create a DateFormatter object for displaying date in specified
// format.
SimpleDateFormat formatter = new SimpleDateFormat(dateFormat,
Locale.getDefault());
// Create a calendar object that will convert the date and time value in
// milliseconds to date.
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(milliSeconds);
return formatter.format(calendar.getTime());
}
This question already has answers here:
java.util.Date format conversion yyyy-mm-dd to mm-dd-yyyy
(8 answers)
Closed 3 years ago.
I need to change the date format using Java from
dd/MM/yyyy to yyyy/MM/dd
How to convert from one date format to another using SimpleDateFormat:
final String OLD_FORMAT = "dd/MM/yyyy";
final String NEW_FORMAT = "yyyy/MM/dd";
// August 12, 2010
String oldDateString = "12/08/2010";
String newDateString;
SimpleDateFormat sdf = new SimpleDateFormat(OLD_FORMAT);
Date d = sdf.parse(oldDateString);
sdf.applyPattern(NEW_FORMAT);
newDateString = sdf.format(d);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
sdf.format(new Date());
This should do the trick
tl;dr
LocalDate.parse(
"23/01/2017" ,
DateTimeFormatter.ofPattern( "dd/MM/uuuu" , Locale.UK )
).format(
DateTimeFormatter.ofPattern( "uuuu/MM/dd" , Locale.UK )
)
2017/01/23
Avoid legacy date-time classes
The answer by Christopher Parker is correct but outdated. The troublesome old date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleTextFormat are now legacy, supplanted by the java.time classes.
Using java.time
Parse the input string as a date-time object, then generate a new String object in the desired format.
The LocalDate class represents a date-only value without time-of-day and without time zone.
DateTimeFormatter fIn = DateTimeFormatter.ofPattern( "dd/MM/uuuu" , Locale.UK ); // As a habit, specify the desired/expected locale, though in this case the locale is irrelevant.
LocalDate ld = LocalDate.parse( "23/01/2017" , fIn );
Define another formatter for the output.
DateTimeFormatter fOut = DateTimeFormatter.ofPattern( "uuuu/MM/dd" , Locale.UK );
String output = ld.format( fOut );
2017/01/23
By the way, consider using standard ISO 8601 formats for strings representing date-time values.
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.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, 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
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
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.
Joda-Time
UPDATE: The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes. This section here is left for the sake of history.
For fun, here is his code adapted for using the Joda-Time library.
// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// import org.joda.time.*;
// import org.joda.time.format.*;
final String OLD_FORMAT = "dd/MM/yyyy";
final String NEW_FORMAT = "yyyy/MM/dd";
// August 12, 2010
String oldDateString = "12/08/2010";
String newDateString;
DateTimeFormatter formatterOld = DateTimeFormat.forPattern(OLD_FORMAT);
DateTimeFormatter formatterNew = DateTimeFormat.forPattern(NEW_FORMAT);
LocalDate localDate = formatterOld.parseLocalDate( oldDateString );
newDateString = formatterNew.print( localDate );
Dump to console…
System.out.println( "localDate: " + localDate );
System.out.println( "newDateString: " + newDateString );
When run…
localDate: 2010-08-12
newDateString: 2010/08/12
Use SimpleDateFormat
String DATE_FORMAT = "yyyy/MM/dd";
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
System.out.println("Formated Date " + sdf.format(date));
Complete Example:
import java.text.SimpleDateFormat;
import java.util.Date;
public class JavaSimpleDateFormatExample {
public static void main(String args[]) {
// Create Date object.
Date date = new Date();
// Specify the desired date format
String DATE_FORMAT = "yyyy/MM/dd";
// Create object of SimpleDateFormat and pass the desired date format.
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
/*
* Use format method of SimpleDateFormat class to format the date.
*/
System.out.println("Today is " + sdf.format(date));
}
}
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date myDate = sdf.parse("28/12/2013");
sdf.applyPattern("yyyy/MM/dd")
String myDateString = sdf.format(myDate);
Now myDateString = 2013/12/28
This is just Christopher Parker's answer adapted to use the new1 classes from Java 8:
final DateTimeFormatter OLD_FORMATTER = DateTimeFormatter.ofPattern("dd/MM/yyyy");
final DateTimeFormatter NEW_FORMATTER = DateTimeFormatter.ofPattern("yyyy/MM/dd");
String oldString = "26/07/2017";
LocalDate date = LocalDate.parse(oldString, OLD_FORMATTER);
String newString = date.format(NEW_FORMATTER);
1 well, not that new anymore, Java 9 should be released soon.
Or you could go the regex route:
String date = "10/07/2010";
String newDate = date.replaceAll("(\\d+)/(\\d+)/(\\d+)", "$3/$2/$1");
System.out.println(newDate);
It works both ways too. Of course this won't actually validate your date and will also work for strings like "21432/32423/52352". You can use "(\\d{2})/(\\d{2})/(\\d{4}" to be more exact in the number of digits in each group, but it will only work from dd/MM/yyyy to yyyy/MM/dd and not the other way around anymore (and still accepts invalid numbers in there like 45). And if you give it something invalid like "blabla" it will just return the same thing back.
many ways to change date format
private final String dateTimeFormatPattern = "yyyy/MM/dd";
private final Date now = new Date();
final DateFormat format = new SimpleDateFormat(dateTimeFormatPattern);
final String nowString = format.format(now);
final Instant instant = now.toInstant();
final DateTimeFormatter formatter =
DateTimeFormatter.ofPattern(
dateTimeFormatPattern).withZone(ZoneId.systemDefault());
final String formattedInstance = formatter.format(instant);
/* Java 8 needed*/
LocalDate date = LocalDate.now();
String text = date.format(formatter);
LocalDate parsedDate = LocalDate.parse(text, formatter);
To Change the format of Date you have Require both format look below.
String stringdate1 = "28/04/2010";
try {
SimpleDateFormat format1 = new SimpleDateFormat("dd/MM/yyyy");
Date date1 = format1.parse()
SimpleDateFormat format2 = new SimpleDateFormat("yyyy/MM/dd");
String stringdate2 = format2.format(date1);
} catch (ParseException e) {
e.printStackTrace();
}
here stringdate2 have date format of yyyy/MM/dd. and it contain 2010/04/28.
SimpleDateFormat format1 = new SimpleDateFormat("yyyy/MM/dd");
System.out.println(format1.format(date));
I want to convert String to Date in different formats.
For example,
I am getting from user,
String fromDate = "19/05/2009"; // i.e. (dd/MM/yyyy) format
I want to convert this fromDate as a Date object of "yyyy-MM-dd" format
How can I do this?
Take a look at SimpleDateFormat. The code goes something like this:
SimpleDateFormat fromUser = new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
String reformattedStr = myFormat.format(fromUser.parse(inputString));
} catch (ParseException e) {
e.printStackTrace();
}
tl;dr
LocalDate.parse(
"19/05/2009" ,
DateTimeFormatter.ofPattern( "dd/MM/uuuu" )
)
Details
The other Answers with java.util.Date, java.sql.Date, and SimpleDateFormat are now outdated.
LocalDate
The modern way to do date-time is work with the java.time classes, specifically LocalDate. The LocalDate class represents a date-only value without time-of-day and without time zone.
DateTimeFormatter
To parse, or generate, a String representing a date-time value, use the DateTimeFormatter class.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" );
LocalDate ld = LocalDate.parse( "19/05/2009" , f );
Do not conflate a date-time object with a String representing its value. A date-time object has no format, while a String does. A date-time object, such as LocalDate, can generate a String to represent its internal value, but the date-time object and the String are separate distinct objects.
You can specify any custom format to generate a String. Or let java.time do the work of automatically localizing.
DateTimeFormatter f =
DateTimeFormatter.ofLocalizedDate( FormatStyle.FULL )
.withLocale( Locale.CANADA_FRENCH ) ;
String output = ld.format( f );
Dump to console.
System.out.println( "ld: " + ld + " | output: " + output );
ld: 2009-05-19 | output: mardi 19 mai 2009
See in action in IdeOne.com.
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, 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.
Use the SimpleDateFormat class:
private Date parseDate(String date, String format) throws ParseException
{
SimpleDateFormat formatter = new SimpleDateFormat(format);
return formatter.parse(date);
}
Usage:
Date date = parseDate("19/05/2009", "dd/MM/yyyy");
For efficiency, you would want to store your formatters in a hashmap. The hashmap is a static member of your util class.
private static Map<String, SimpleDateFormat> hashFormatters = new HashMap<String, SimpleDateFormat>();
public static Date parseDate(String date, String format) throws ParseException
{
SimpleDateFormat formatter = hashFormatters.get(format);
if (formatter == null)
{
formatter = new SimpleDateFormat(format);
hashFormatters.put(format, formatter);
}
return formatter.parse(date);
}
Convert a string date to java.sql.Date
String fromDate = "19/05/2009";
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
java.util.Date dtt = df.parse(fromDate);
java.sql.Date ds = new java.sql.Date(dtt.getTime());
System.out.println(ds);//Mon Jul 05 00:00:00 IST 2010
Check the javadocs for java.text.SimpleDateFormat It describes everything you need.
While SimpleDateFormat will indeed work for your needs, additionally you might want to check out Joda Time, which is apparently the basis for the redone Date library in Java 7. While I haven't used it a lot, I've heard nothing but good things about it and if your manipulating dates extensively in your projects it would probably be worth looking into.
Simple way to format a date and convert into string
Date date= new Date();
String dateStr=String.format("%td/%tm/%tY", date,date,date);
System.out.println("Date with format of dd/mm/dd: "+dateStr);
output:Date with format of dd/mm/dd: 21/10/2015
Suppose that you have a string like this :
String mDate="2019-09-17T10:56:07.827088"
Now we want to change this String format separate date and time in Java and Kotlin.
JAVA:
we have a method for extract date :
public String getDate() {
try {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.US);
Date date = dateFormat.parse(mDate);
dateFormat = new SimpleDateFormat("MM/dd/yyyy", Locale.US);
return dateFormat.format(date);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
Return is this : 09/17/2019
And we have method for extract time :
public String getTime() {
try {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.US);
Date date = dateFormat.parse(mCreatedAt);
dateFormat = new SimpleDateFormat("h:mm a", Locale.US);
return dateFormat.format(date);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
Return is this : 10:56 AM
KOTLIN:
we have a function for extract date :
fun getDate(): String? {
var dateFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.US)
val date = dateFormat.parse(mDate!!)
dateFormat = SimpleDateFormat("MM/dd/yyyy", Locale.US)
return dateFormat.format(date!!)
}
Return is this : 09/17/2019
And we have method for extract time :
fun getTime(): String {
var dateFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.US)
val time = dateFormat.parse(mDate!!)
dateFormat = SimpleDateFormat("h:mm a", Locale.US)
return dateFormat.format(time!!)
}
Return is this : 10:56 AM
A Date object has no format, it is a representation. The date can be presented by a String with the format you like.
E.g. "yyyy-MM-dd", "yy-MMM-dd", "dd-MMM-yy" and etc.
To acheive this you can get the use of the SimpleDateFormat
Try this,
String inputString = "19/05/2009"; // i.e. (dd/MM/yyyy) format
SimpleDateFormat fromUser = new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
Date dateFromUser = fromUser.parse(inputString); // Parse it to the exisitng date pattern and return Date type
String dateMyFormat = myFormat.format(dateFromUser); // format it to the date pattern you prefer
System.out.println(dateMyFormat); // outputs : 2009-05-19
} catch (ParseException e) {
e.printStackTrace();
}
This outputs : 2009-05-19
There are multiple ways to do it, but a very practical one is the use String.format which you can use with java.util.Date or java.util.Calendar or event java.time.LocalDate.
String.format is backed by java.util.Formatter.
I like the omnivore take on it.
class Playground {
public static void main(String[ ] args) {
String formatString = "Created on %1$td/%1$tm/%1$tY%n";
System.out.println(String.format(formatString, new java.util.Date()));
System.out.println(String.format(formatString, java.util.Calendar.getInstance()));
System.out.println(String.format(formatString, java.time.LocalDate.now()));
}
}
The output will be in all cases:
Created on 04/12/2022
Created on 04/12/2022
Created on 04/12/2022