// 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")) ;
Related
I am creating a DSL with ANTLR 4, and I wonder if it is possible to convert several date format (string) to date with the same function without passing the format for example if my DSL is like that
date1 = "2020-05-08"
date2 = "2020/05/08"
date3 = "20200508"
...
and in my java code I convert the string directly to date without knowing the format for example
Date date1 = convertToDate(date1);
Date date2 = convertToDate(date2);
Date date1 = convertToDate(date3);
instead of writing
Date date1 = convertToDate(date1,"yyyy-mm-dd");
Date date2 = convertToDate(date2,"yyyy/mm/dd");
Date date1 = convertToDate(date3,"yyyymmdd");
Since Java 8, which introduced the new Date and Time API, you are no longer advised to use Date, Calendar, SimpleDateFormat and so on. Those are now legacy types.
Also, if you intend to parse the month, you are supposed to use MM instead of mm (which indicates minutes).
With the new Date and Time API, you could use DateTimeFormatter with optional patterns using [ and ]. Then you can parse the string dates to LocalDate instances, as shown below:
DateTimeFormatter dateFormatter = new DateTimeFormatterBuilder()
.appendPattern("[yyyy-MM-dd]")
.appendPattern("[yyyy/MM/dd]")
.appendPattern("[yyyyMMdd]")
.toFormatter();
LocalDate date1 = LocalDate.parse("2020-05-08", dateFormatter);
LocalDate date2 = LocalDate.parse("2020/05/08", dateFormatter);
LocalDate date3 = LocalDate.parse("20200508", dateFormatter);
System.out.println(date1);
System.out.println(date2);
System.out.println(date3);
In the example you've passed you can remove all non digit symbols to use only one convert function. Ex:
date1 = "2020-05-08"
date2 = "2020/05/08"
date3 = "20200508"
...
dateN = removeSymbols(dateN);
Date date = convertToDate(dateN,"yyyymmdd");
To remove the non digit you can use this function:
dateN = dateN.replaceAll("\\D", "");
You should be able to accomplish this with a simple regex.
Pattern datePattern = Pattern.compile("^(?<Year>\\d{4})[/-]?(?<Month>\\d{2})[/-]?(?<Day>\\d{2})$")
Then build the date with the match groups.
Is there any way in java(java.util.* or Joda api ) to convert "2020-04-03 20:17:46" to "yyyy-MM-dd'T'HH:mm:ss"
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss")
.parse("2020-04-03 20:17:46")
its giving java.text.parseException always
Just for the case you are using Java 8 or above, make use of java.time.
See this simple example:
public static void main(String[] args) {
// example datetime
String datetime = "2020-04-03 20:17:46";
// create a formatter that parses datetimes of this pattern
DateTimeFormatter parserDtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
// then parse the datetime with that formatter
LocalDateTime ldt = LocalDateTime.parse(datetime, parserDtf);
// in order to output the parsed datetime, use the default formatter (implicitly)
System.out.println(ldt);
// or format it in a totally different way
System.out.println(ldt.format(
DateTimeFormatter.ofPattern("EEE, dd. 'of' MMM 'at' hh-mm-ss a",
Locale.ENGLISH)
)
);
}
This outputs
2020-04-03T20:17:46
Fri, 03. of Apr at 08-17-46 PM
Please note that this doesn't consider any time zone or offset, it just represents a date and time consisting of the passed or parsed years, months, days, hours, minutes and seconds, nothing else.
Do not use Date/Time API from java.util.* as most of them are now outdated. Use java.time API instead.
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) throws IOException {
String strDatetime = "2020-04-03 20:17:46";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime parsedDate = LocalDateTime.parse(strDatetime, formatter);
System.out.println(parsedDate);
}
}
Output:
2020-04-03T20:17:46
Learn more about DateTimeFormatter at https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html
Could this help you? http://tutorials.jenkov.com/java-internationalization/simpledateformat.html
First you need to parse the String with the old format, you will get a Date object. Then Create a new SimpleDateFormat with your new format, then you can format the Date object.
String dateString = "2020-04-03 20:17:46";
SimpleDateFormat output = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = sdf.parse(dateString);
String formattedDate = output.format(date);
It do not work that way directly but if you still want to do it then, here is the process.
Create an object of SimpleDateFormat with pattern "yyyy-MM-dd HH:mm:ss")
use this to parse the string. Ultimately you are going to get date in both cases. Is there any specific reason for using T in pattern for dates which do not contain them?
Use LocalDateTime.
Timestamp timestamp = Timestamp.parse("2020-04-03 20:17:46");
LocalDateTime localDateTime = timestamp.toLocalDateTime();
System.out.println(localDateTime); // 2020-04-03T20:17:46
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
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());
How can I take a string in a format such as: 2008-06-02 00:00:00.0 and convert it to: 02-Jun-2008?
Can I somehow take the original string, convert it to a Date object, then use a formatter to get the final output (rather than parsing the string myself)? Thanks!
You can use SimpleDateFormat to convert between a String and a Date object and vice versa based on a pattern. Click the API link, you'll see patterns being explained in detail. A 4-digit year can be represented with yyyy, a 3-character month abbreviation can be represented with MMM and so on.
First you need to parse the String of the first format into a Date object:
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Date date = sdf1.parse(inputString);
Then you need to format the Date into a String of the second format:
SimpleDateFormat sdf2 = new SimpleDateFormat("dd-MMM-yyyy", Locale.ENGLISH);
String outputString = sdf2.format(date);
Note that you need to take the Locale into account as well to get the month to be printed in English, else it will use the platform's default locale to translate the month.
Use 2 instances of SimpleDateFormat class. One for converting your input string to date and second to convert date back to string but in another format.
Here is an example of using SimpleDateFormat.
DateFormat startFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
DateFormat endFormat = new SimpleDateFormat("dd-MM-yyyy");
String outputString = null;
try {
Date date = startFormat.parse(inputString);
outputString = endFormat.format(date);
} catch(ParseException pe) {
throw new IllegalArgumentException(inputString + " is not properly formated.", pe);
}
You can definitely use SimpleDateFormat class like others have recommended.
Another suggestion if it applies in your case. If you are getting this data from a sql query you can also use to_char() method to format it in the query itself. For example: to_char(column_name,'DD-MON-YYYY')