I want to save the console into .txt like this
every time i run the app.
Here's how I use for saving the console based on the current time:
SimpleDateFormat dtf = new SimpleDateFormat("yyMMdd");
Date date = new Date();
System.setOut(new PrintStream(new FileOutputStream("Data_Bank_" + dtf.format(date) + ".txt")));
However, when I put the run configuration arguments with
I want it to automatically formatted into yyMMdd too. Not like
Does anyone know how to do that???? Thanks anyway..
If you can use Java 8 or higher, then it's recommended to use java.time for operations with dates and times.
You can solve your problem with LocalDate and DateTimeFormatter:
public static void main(String[] args) {
// get the date of today
LocalDate today = LocalDate.now();
// and parse a given date with a
LocalDate someDate = LocalDate.parse("2020-01-24");
// define a formatter using your desired date pattern
DateTimeFormatter dtfShort = DateTimeFormatter.ofPattern("yyMMdd");
// print the dates using a built-in formatter
System.out.println("[ISO]\t" + today.format(DateTimeFormatter.ISO_LOCAL_DATE)
+ "\t" + someDate.format(DateTimeFormatter.ISO_LOCAL_DATE));
// print the dates using your custom formatter
System.out.println("[Short]\t" + today.format(dtfShort)
+ "\t\t" + someDate.format(dtfShort));
}
The output is this:
[ISO] 2020-01-22 2020-01-24
[Short] 200122 200124
Should be easy to use for file output, which should be done with java.nio nowadays.
Assuming you have input date i will parse the date and do something like this and save that for file,
String input = "Thu Jun 18 20:56:02 EDT 2009";
SimpleDateFormat parser = new SimpleDateFormat("EEE MMM d HH:mm:ss zzz yyyy");
Date date = parser.parse(input);
SimpleDateFormat formatter = new SimpleDateFormat("yyMMdd");
String formattedDate = formatter.format(date);
.......
System.setOut(new PrintStream(new FileOutputStream("Data_Bank_"+formattedDate +".txt")));
You'll need to parse the String that you're passing as an argument. You're on the right track with SimpleDateFormat. You just need to parse the input and then convert it to the format you're looking for using the parse method on the SimpleDateFormat
Something like:
public static void main(String[] args) {
try {
SimpleDateFormat input = new SimpleDateFormat("yyyy-MM-dd");
Date inputDate = input.parse(args[0]);
SimpleDateFormat output = new SimpleDateFormat("yyMMdd");
System.out.println(output.format(inputDate));
}catch(ParseException parseException) {
//handle error
parseException.printStackTrace();
}
}
The java docs on date parsing are pretty good. Read more here:
https://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html
Dates get complex quickly in Java. Learn more about options in Java 8 and LocalDate here:
https://www.baeldung.com/java-8-date-time-intro
https://www.baeldung.com/java-string-to-date
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
You may google examples on how to use them, better to use the latest classes
Related
// input format: dd/MM/yy
SimpleDateFormat parser = new SimpleDateFormat("dd/MM/yy");
// output format: yyyy-MM-dd
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(formatter.format(parser.parse("12/1/20"))); // 0020-11-01
I am using the above code but it is giving me year as '0020' instead of '2020'.
Use java.time for this:
public static void main(String[] args) {
String dateString = "12/1/20";
LocalDate localDate = LocalDate.parse(dateString, DateTimeFormatter.ofPattern("dd/M/yy"));
System.out.println(localDate.format(DateTimeFormatter.ISO_LOCAL_DATE));
}
The output is
2020-01-12
Pay attention to the amount of M in the patterns, you cannot parse a String that contains a single digit for a month using a double M here.
Most Java devs would be tempted to answer SimpleDateFormat but it's not thread safe.
So I recommend you use Java 8 DateFormat.
Assuming your current Date is a String:
DateFormat dateFormat = new DateFormat("yyyy-MM-dd") ;
String dateString ="20/4/20";
LocalDate date = LocalDate.parse(dateString, dateFormat);
If you are using less than Java 8 use joda time for the same classes.
Once you have converted it as a date object use required format and use LocalDate.
format(date, new DateFormat("yyyy-MM-dd")) ;
I will be direct with my question. I am wondering why I can't parse a fromat MMM-dd-yyyy into yyyy-MM-dd (java.sql.Date format)? Any suggestion on how I am going to convert a String into a format of (yyyy-MM-dd)?
Here is the code:
public DeadlineAction(String deadline){
putValue(NAME, deadline);
deadLine = deadline;
SimpleDateFormat formatter = new SimpleDateFormat("yyyy MM dd");
try {
finalDate = (Date) formatter.parse(deadLine);
}catch(ParseException e) {
JOptionPane.showMessageDialog(null, e.getMessage(),"Error",JOptionPane.ERROR_MESSAGE);
}
}
Thank you
Basically, you can't parse a String in the format of MMM-dd-yyyy using the format of yyyy MM dd, it just doesn't make sense, you need one formatter to parse the value and another to format itm for example
SimpleDateFormat to = new SimpleDateFormat("yyyy MM dd");
SimpleDateFormat from = new SimpleDateFormat("MMM-dd-yyyy");
Date date = from.parse(deadLine);
String result = to.format(date)
The question that needs to be asked is, why you would bother. If your intention is to put this value into the database, you should be creating an instance of java.sql.Date (from the java.util.Date) and using PreparedStatement#setDate to apply it to your query, then letting the JDBC driver deal with it
The answer by MadProgrammer is correct. You must define a formatting pattern to fit the format of your input data string.
You could avoid the problem in the first place by using the java.time framework.
java.time
The java.time framework is built into Java 8 and later (also back-ported to Java 6 & 7 and to Android). These classes supplant the old troublesome legacy date-time classes (java.util.Date/.Calendar).
ISO 8601
Your input strings are apparent is standard ISO 8601 format, YYYY-MM-DD such as 2016-01-23.
The java.time classes use ISO 8601 formats by default when parsing/generating strings that represent date-time values. So no need to specify a formatting pattern.
Parsing string
For a date-only value without time-of-day and without time zone, use LocalDate class.
LocalDate localDate = LocalDate.parse( "2016-01-23" );
Generating string
To generate a string representing that LocalDate object’s value, just call toString to get a string in ISO 8601 format.
String output = localDate.toString(); // 2016-01-23
For other formats, use the java.time.format package. Usually best to let java.time automatically localize to the user’s human language and cultural norms defined by a Locale.
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDate( FormatStyle.MEDIUM );
Locale locale = Locale.CANADA_FRENCH;
formatter = formatter.withLocale( locale );
String output = localDate.format( formatter );
Or you can specify your own particular pattern. Note that you should still specify a Locale to determine aspects such as the name-of-month or name-of-day. Here is a demo of the pattern that seems to be asked in the Question (not sure as Question is unclear).
DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "MMM-dd-yyyy" );
Locale locale = Locale.US;
formatter = formatter.withLocale( locale );
String output = localDate.format( formatter );
Try something like:
try {
final String deadLine = "Oct-12-2006";
SimpleDateFormat formatter = new SimpleDateFormat("MMM-dd-yyyy");//define formatter for yout date time
Date finalDate = formatter.parse(deadLine);//parse your string as Date
SimpleDateFormat formatter2 = new SimpleDateFormat("yyyy-MM-dd");// define your desired format
System.out.println(formatter2.format(finalDate));//format the string to your desired date format
} catch (Exception e) {
//handle
}
Your example is not unparseable. I removed the dashes from MMM-dd-yyyy to MMM dd yyyy. You can put them back if needed. I also removed the any extra code to make the solution clear.
import java.sql.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
public DeadlineAction(String deadline){
//if deadline has format similar to "December 19 2011"
try {
finalDate = new java.sql.Date(
((java.util.Date) new SimpleDateFormat("MMM dd yyyy").parse(deadline)).getTime());
}catch(ParseException e) {
//Your exception code
e.printStackTrace();
}
}
This works for almost every conversion to sqlDate. Just change SimpleDateFormat("MMM dd yyyy") to what you need it to be.
Example: new SimpleDateFormat("MMM-yyyy-dd").parse("NOVEMBER-2012-30")
I have a date in the format MM/DD/YYYY and time in the format HHMM (24 hour time w/o the colon). Both of these strings are in an array. I would like to store this as one string - maybe something like "MM-DD-YYYY HH:MM" - and then be able to convert it to a written date like "January 1, 2014 16:15" when I am showing it to the user. How can I do this?
This is the code that I have:
String date = "05/27/2014 23:01";
Date df = new SimpleDateFormat("MM/DD/YYYY HH:mm").parse(date);
System.out.println(df);
However this is what I get: "Sun Dec 29 23:01:00 EST 2013"
The output I am looking for is: "December 29, 2013 23:01"
SimpleDateFormat is the way to go; to parse your Strings in the required meaningful date and time formats and finally print your date as a required String.
You specify the 2 formats as follows:
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
SimpleDateFormat timeFormat = new SimpleDateFormat("HHmm");
Considering a simple hardcoded array of date and time (not the best way to show but your question calls it an array):
String[] array = { "12/31/2013", "1230" };
You would have to set these parsed dates in a Calendar instance:
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.HOUR, time.getHours());
cal.add(Calendar.MINUTE, time.getMinutes());
Finally format your date using the same SimpleDateFormat
SimpleDateFormat newFormat = new SimpleDateFormat("MMMM dd, yyyy 'at' hh:mm");
Here is the complete working code:
public class DateExample {
public static void main(String[] args) {
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
SimpleDateFormat timeFormat = new SimpleDateFormat("HHmm");
String[] array = { "12/31/2013", "1230" };
try {
Date date = dateFormat.parse(array[0]);
Date time = timeFormat.parse(array[1]);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.HOUR, time.getHours());
cal.add(Calendar.MINUTE, time.getMinutes());
SimpleDateFormat newFormat = new SimpleDateFormat(
"MMMM dd, yyyy 'at' hh:mm");
String datePrint = newFormat.format(cal.getTime());
System.out.println(datePrint);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
The output:
December 31, 2013 at 12:30
Unfortunately, none of the existing answers has mentioned the root cause of the problem which is as follows:
You have used D (which specifies Day in year) instead of d (Day in month).
You have used Y (which specifies Week year) instead of y (Year).
Learn more about it at the documentation page. Now that you have understood the root cause of the problem, let's focus on the solution using the best standard API of the time.
java.time
The legacy date-time API (java.util date-time types and their formatting API, SimpleDateFormat) is outdated and error-prone. It is recommended to stop using it completely and switch to java.time, the modern date-time API*.
I would solve it in the following steps:
Parse the date string into LocalDate.
Parse the time string into LocalTime.
Combine the objects of LocalDate and LocalTime to obtain an object of LocalDateTime.
Format the object of LocalDateTime into the desired pattern.
Demo using the modern API:
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
// 1. Parse the date string into `LocalDate`.
DateTimeFormatter dateParser = DateTimeFormatter.ofPattern("M/d/u", Locale.ENGLISH);
LocalDate date = LocalDate.parse("01/01/2014", dateParser);
// 2. Parse the time string into `LocalTime`.
DateTimeFormatter timeParser = DateTimeFormatter.ofPattern("HHmm", Locale.ENGLISH);
LocalTime time = LocalTime.parse("1615", timeParser);
// 3. Combine date and time to obtain an object of `LocalDateTime`.
LocalDateTime ldt = date.atTime(time);
// 4. Format the object of `LocalDateTime` into the desired pattern.
DateTimeFormatter dtfOutput = DateTimeFormatter.ofPattern("MMMM d, uuuu HH:mm", Locale.ENGLISH);
String output = dtfOutput.format(ldt);
System.out.println(output);
}
}
Output:
January 1, 2014 16:15
Learn more about the the modern date-time API* from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.
You can use java.text.DateFormat class to convert date to string(format method), and string to date(parse method).
You can use SimpleDateFormat both to parse Strings into dates and to format Dates back into Strings. Here's your example:
SimpleDateFormat parser = new SimpleDateFormat("MM/DD/YYYY HH:mm");
SimpleDateFormat formatter = new SimpleDateFormat("MMMM dd, yyyy HH:mm");
String dateString = "05/27/2014 23:01";
Date parsedDate = parser.parse(dateString);
String formattedDateString = formatter.format(parsedDate);
System.out.println("Read String '" + dateString + "' as '" + parsedDate + "', formatted as '" + formattedDateString + "'");
When I run this, I get:
Read String '05/27/2014 23:01' as 'Sun Dec 29 23:01:00 EST 2013', formatted as 'December 29, 2013 23:01'
Goal
Convert String to Date with the format you have it in
Output that date as a String in the format you want
Code:
String date = "05/27/2014 23:01";
//convert the String to Date based on its existing format
Date df = new SimpleDateFormat("MM/dd/yyyy HH:mm").parse(date);
System.out.println("date " +df);
//now output the Date as a string in the format you want
SimpleDateFormat dt1 = new SimpleDateFormat("MMMM dd, yyyy HH:mm");
System.out.println(dt1.format(df));
Output:
date Tue May 27 23:01:00 CDT 2014
May 27, 2014 23:01
you can use this >>
String s = sd.format(d);
String s1 = sd1.format(d);
Here Is the full code >>
import java.text.SimpleDateFormat;
import java.util.Date;
public class dt {
public static void main(String[] args) {
// TODO Auto-generated method stub
Date d = new Date();
SimpleDateFormat sd = new SimpleDateFormat("MMMM dd, YYYY");
SimpleDateFormat sd1 = new SimpleDateFormat("HH:mm");
String s = sd.format(d);
String s1 = sd1.format(d);
System.out.println(s +" "+ s1);
}
}
You should have bothered to do a bit of searching before posting. StackOverflow.com has many questions and answers like this already.
But for the sake of posterity, here's some example code using the Joda-Time 2.3 library. Avoid the java.util.Date/Calendar classes bundled with Java as they are badly designed and implemented. In Java 8, continue to use Joda-Time or switch to the new java.time.* classes defined by JSR 310: Date and Time API. Those new classes were inspired by Joda-Time but are entirely re-architected.
Joda-Time has many features aimed at formatting output. Joda-Time offers built-in standard (ISO 8601) formats. Some classes render strings with format and language appropriate to the host computer's locale, or you can specify a locale. And Joda-Time lets you define your own funky formats as well. Searching for "joda" + "format" will get you many examples.
// © 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.*;
String input = "05/27/2014" + " " + "23:01";
Parse that string…
// Assuming that string is for UTC/GMT, pass the built-in constant "DateTimeZone.UTC".
// If that string was stored as-is for a specific time zone (NOT a good idea), pass an appropriate DateTimeZone instance.
DateTimeFormatter formatterInput = DateTimeFormat.forPattern( "MM/dd/yyyy HH:mm" ).withZone( DateTimeZone.UTC );
DateTime dateTime = formatterInput.parseDateTime( input );
Ideally you would store the values in an appropriate date-time format in a database. If not possible, then store as a string in ISO 8601 format, set to UTC/GMT (no time zone offset).
// Usually best to write out date-times in ISO 8601 format in the UTC time zone (no time zone offset, 'Z' = Zulu).
String saveThisStringToStorage = dateTime.toDateTime( DateTimeZone.UTC ).toString(); // Convert to UTC if not already in UTC.
Do your business logic and storage in UTC generally. Switch to local time zones and localized formatting only in the user-interface portion of your app.
// Convert to a localized format (string) only as needed in the user-interface, using the user's time zone.
DateTimeFormatter formatterOutput = DateTimeFormat.mediumDateTime().withLocale( Locale.US ).withZone( DateTimeZone.forID( "America/New_York" ) );
String showUserThisString = formatterOutput.print( dateTime );
Dump to console…
System.out.println( "input: " + input );
System.out.println( "dateTime: " + dateTime );
System.out.println( "saveThisStringToStorage: " + saveThisStringToStorage );
System.out.println( "showUserThisString: " + showUserThisString );
When run…
input: 05/27/2014 23:01
dateTime: 2014-05-27T23:01:00.000Z
saveThisStringToStorage: 2014-05-27T23:01:00.000Z
showUserThisString: May 27, 2014 7:01:00 PM
I want to convert a java.util.Date object to a String in Java.
The format is 2010-05-30 22:15:52
Convert a Date to a String using DateFormat#format method:
String pattern = "MM/dd/yyyy HH:mm:ss";
// Create an instance of SimpleDateFormat used for formatting
// the string representation of date according to the chosen pattern
DateFormat df = new SimpleDateFormat(pattern);
// Get the today date using Calendar object.
Date today = Calendar.getInstance().getTime();
// Using DateFormat format method we can create a string
// representation of a date with the defined format.
String todayAsString = df.format(today);
// Print the result!
System.out.println("Today is: " + todayAsString);
From http://www.kodejava.org/examples/86.html
Format formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String s = formatter.format(date);
Commons-lang DateFormatUtils is full of goodies (if you have commons-lang in your classpath)
//Formats a date/time into a specific pattern
DateFormatUtils.format(yourDate, "yyyy-MM-dd HH:mm:SS");
tl;dr
myUtilDate.toInstant() // Convert `java.util.Date` to `Instant`.
.atOffset( ZoneOffset.UTC ) // Transform `Instant` to `OffsetDateTime`.
.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME ) // Generate a String.
.replace( "T" , " " ) // Put a SPACE in the middle.
2014-11-14 14:05:09
java.time
The modern way is with the java.time classes that now supplant the troublesome old legacy date-time classes.
First convert your java.util.Date to an Instant. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Conversions to/from java.time are performed by new methods added to the old classes.
Instant instant = myUtilDate.toInstant();
Both your java.util.Date and java.time.Instant are in UTC. If you want to see the date and time as UTC, so be it. Call toString to generate a String in standard ISO 8601 format.
String output = instant.toString();
2014-11-14T14:05:09Z
For other formats, you need to transform your Instant into the more flexible OffsetDateTime.
OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC );
odt.toString(): 2020-05-01T21:25:35.957Z
See that code run live at IdeOne.com.
To get a String in your desired format, specify a DateTimeFormatter. You could specify a custom format. But I would use one of the predefined formatters (ISO_LOCAL_DATE_TIME), and replace the T in its output with a SPACE.
String output = odt.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME )
.replace( "T" , " " );
2014-11-14 14:05:09
By the way I do not recommend this kind of format where you purposely lose the offset-from-UTC or time zone information. Creates ambiguity as to the meaning of that string’s date-time value.
Also beware of data loss, as any fractional second is being ignored (effectively truncated) in your String’s representation of the date-time value.
To see that same moment through the lens of some particular region’s wall-clock time, apply a ZoneId to get a ZonedDateTime.
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );
zdt.toString(): 2014-11-14T14:05:09-05:00[America/Montreal]
To generate a formatted String, do the same as above but replace odt with zdt.
String output = zdt.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME )
.replace( "T" , " " );
2014-11-14 14:05:09
If executing this code a very large number of times, you may want to be a bit more efficient and avoid the call to String::replace. Dropping that call also makes your code shorter. If so desired, specify your own formatting pattern in your own DateTimeFormatter object. Cache this instance as a constant or member for reuse.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-MM-dd HH:mm:ss" ); // Data-loss: Dropping any fractional second.
Apply that formatter by passing the instance.
String output = zdt.format( f );
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old date-time classes such as java.util.Date, .Calendar, & java.text.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.
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP (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.
Altenative one-liners in plain-old java:
String.format("The date: %tY-%tm-%td", date, date, date);
String.format("The date: %1$tY-%1$tm-%1$td", date);
String.format("Time with tz: %tY-%<tm-%<td %<tH:%<tM:%<tS.%<tL%<tz", date);
String.format("The date and time in ISO format: %tF %<tT", date);
This uses Formatter and relative indexing instead of SimpleDateFormat which is not thread-safe, btw.
Slightly more repetitive but needs just one statement.
This may be handy in some cases.
Why don't you use Joda (org.joda.time.DateTime)?
It's basically a one-liner.
Date currentDate = GregorianCalendar.getInstance().getTime();
String output = new DateTime( currentDate ).toString("yyyy-MM-dd HH:mm:ss");
// output: 2014-11-14 14:05:09
It looks like you are looking for SimpleDateFormat.
Format: yyyy-MM-dd kk:mm:ss
In single shot ;)
To get the Date
String date = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(new Date());
To get the Time
String time = new SimpleDateFormat("hh:mm", Locale.getDefault()).format(new Date());
To get the date and time
String dateTime = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.getDefaut()).format(new Date());
Happy coding :)
public static String formateDate(String dateString) {
Date date;
String formattedDate = "";
try {
date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss",Locale.getDefault()).parse(dateString);
formattedDate = new SimpleDateFormat("dd/MM/yyyy",Locale.getDefault()).format(date);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return formattedDate;
}
If you only need the time from the date, you can just use the feature of String.
Date test = new Date();
String dayString = test.toString();
String timeString = dayString.substring( 11 , 19 );
This will automatically cut the time part of the String and save it inside the timeString.
Here are examples of using new Java 8 Time API to format legacy java.util.Date:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss:SSS Z")
.withZone(ZoneOffset.UTC);
String utcFormatted = formatter.format(date.toInstant());
ZonedDateTime utcDatetime = date.toInstant().atZone(ZoneOffset.UTC);
String utcFormatted2 = utcDatetime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss:SSS Z"));
// gives the same as above
ZonedDateTime localDatetime = date.toInstant().atZone(ZoneId.systemDefault());
String localFormatted = localDatetime.format(DateTimeFormatter.ISO_ZONED_DATE_TIME);
// 2011-12-03T10:15:30+01:00[Europe/Paris]
String nowFormatted = LocalDateTime.now().toString(); // 2007-12-03T10:15:30.123
It is nice about DateTimeFormatter that it can be efficiently cached as it is thread-safe (unlike SimpleDateFormat).
List of predefined fomatters and pattern notation reference.
Credits:
How to parse/format dates with LocalDateTime? (Java 8)
Java8 java.util.Date conversion to java.time.ZonedDateTime
Format Instant to String
What's the difference between java 8 ZonedDateTime and OffsetDateTime?
The easiest way to use it is as following:
currentISODate = new Date().parse("yyyy-MM-dd'T'HH:mm:ss", "2013-04-14T16:11:48.000");
where "yyyy-MM-dd'T'HH:mm:ss" is the format of the reading date
output: Sun Apr 14 16:11:48 EEST 2013
Notes: HH vs hh
- HH refers to 24h time format
- hh refers to 12h time format
public static void main(String[] args)
{
Date d = new Date();
SimpleDateFormat form = new SimpleDateFormat("dd-mm-yyyy hh:mm:ss");
System.out.println(form.format(d));
String str = form.format(d); // or if you want to save it in String str
System.out.println(str); // and print after that
}
Let's try this
public static void main(String args[]) {
Calendar cal = GregorianCalendar.getInstance();
Date today = cal.getTime();
DateFormat df7 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
String str7 = df7.format(today);
System.out.println("String in yyyy-MM-dd format is: " + str7);
} catch (Exception ex) {
ex.printStackTrace();
}
}
Or a utility function
public String convertDateToString(Date date, String format) {
String dateStr = null;
DateFormat df = new SimpleDateFormat(format);
try {
dateStr = df.format(date);
} catch (Exception ex) {
ex.printStackTrace();
}
return dateStr;
}
From Convert Date to String in Java
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String date = "2010-05-30 22:15:52";
java.util.Date formatedDate = sdf.parse(date); // returns a String when it is parsed
System.out.println(sdf.format(formatedDate)); // the use of format function returns a String
Date date = new Date();
String strDate = String.format("%tY-%<tm-%<td %<tH:%<tM:%<tS", date);
One Line option
This option gets a easy one-line to write the actual date.
Please, note that this is using Calendar.class and SimpleDateFormat, and then it's not
logical to use it under Java8.
yourstringdate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime());
Is there a method in Java that I can use to convert MM/DD/YYYY to DD-MMM-YYYY?
For example: 05/01/1999 to 01-MAY-99
Use a SimpleDateFormat to parse the date and then print it out with a SimpleDateFormat withe the desired format.
Here's some code:
SimpleDateFormat format1 = new SimpleDateFormat("MM/dd/yyyy");
SimpleDateFormat format2 = new SimpleDateFormat("dd-MMM-yy");
Date date = format1.parse("05/01/1999");
System.out.println(format2.format(date));
Output:
01-May-99
java.time
You should use java.time classes with Java 8 and later. To use java.time, add:
import java.time.* ;
Below is an example, how you can format date.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MMM-yyyy");
String date = "15-Oct-2018";
LocalDate localDate = LocalDate.parse(date, formatter);
System.out.println(localDate);
System.out.println(formatter.format(localDate));
Try this,
Date currDate = new Date();
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
String strCurrDate = dateFormat.format(currDate);
System.out.println("strCurrDate->"+strCurrDate);
final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
LocalDate localDate = LocalDate.now();
System.out.println("Formatted Date: " + formatter.format(localDate));
Java 8 LocalDate
Try this
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); // Set your date format
String currentData = sdf.format(new Date());
java.time
The java.util Date-Time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.
A Date-Time parsing/formatting type is Locale-sensitive
A Date-Time parsing/formatting type (e.g. DateTimeFormatter) is Locale-sensitive i.e. the same letters will produce the text in different Locales .e.g. MMM is used for the three-letter abbreviation of month name and it can be different words in different Locales. In the absence of the Locale parameter, it will use the JVM's Locale. Therefore, never forget to use a Date-Time parsing/formatting type without the Locale parameter. Learn more about it from Never use SimpleDateFormat or DateTimeFormatter without a Locale.
You need two instances of DateTimeFormatter - one to parse the input string and another to format the output string, as per required patterns.
Demo:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
DateTimeFormatter dtfInput = DateTimeFormatter.ofPattern("MM/dd/uuuu", Locale.ENGLISH);
String strDate = "05/01/1999";
LocalDate date = LocalDate.parse(strDate, dtfInput);
// The default string i.e. the value returned by LocalDate#toString
System.out.println(date);
DateTimeFormatter dtfOutputEng = DateTimeFormatter.ofPattern("dd-MMM-uuuu", Locale.ENGLISH);
String formattedEng = dtfOutputEng.format(date);
System.out.println(formattedEng);
DateTimeFormatter dtfOutputFr = DateTimeFormatter.ofPattern("dd-MMM-uuuu", Locale.FRENCH);
String formattedFr = dtfOutputFr.format(date);
System.out.println(formattedFr);
}
}
Output:
1999-05-01
01-May-1999
01-mai-1999
ONLINE DEMO
Some other important notes:
Instead of Y (week-based-year), you need to use y (year-of-era) and instead of D (day-of-year), you need to use d (day-of-month). Check the documentation to learn more about it.
Here, you can use y instead of u but I prefer u to y.
Learn more about the modern Date-Time API* from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.
Below should work.
SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy");
Date oldDate = df.parse(df.format(date)); //this date is your old date object
formatter = new SimpleDateFormat("dd-MMM-yy");