Name a file in Java to include date and time stamp - java

I am exporting data into a file in a Java application using NetBeans. The file will have a hard coded name given by me in the code. Please find below the code.
private static String FILE = "D:\\Report.pdf";
I want to append date and time stamp to the file name generated so that each file created is a unique file. How to achieve this?

tl;dr
"Report" + "_"
+ Instant.now() // Capture the current moment in UTC.
.truncatedTo( ChronoUnit.SECONDS ) // Lop off the fractional second, as superfluous to our purpose.
.toString() // Generate a `String` with text representing the value of the moment in our `Instant` using standard ISO 8601 format: 2016-10-02T19:04:16Z
.replace( "-" , "" ) // Shorten the text to the “Basic” version of the ISO 8601 standard format that minimizes the use of delimiters. First we drop the hyphens from the date portion
.replace( ":" , "" ) // Returns 20161002T190416Z afte we drop the colons from the time portion.
+ ".pdf"
Report_20161002T190416Z.pdf
Or define a formatter for this purpose. The single-quote marks ' mean “ignore this chunk of text; expect the text, but do not interpret”.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "'Report_'uuuuMMdd'T'HHmmss'.pdf'" ) ;
String fileName = OffsetDateTime.now( ZoneOffset.UTC ).truncatedTo( ChronoUnit.SECONDS ).format( f ) ;
Use same formatter to parse back to a date-time value.
OffsetDateTime odt = OffsetDateTime.parse( "Report_20161002T190416Z.pdf" , f ) ;
java.time
The other Answers are correct but outdated. The troublesome old legacy date-time classes are now supplanted by the java.time classes.
Get the current moment as 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).
Instant instant = Instant.now(); // 2016-10-02T19:04:16.123456789Z
Truncate fractional second
You probably want to remove the fractional second.
Instant instant = Instant.now().truncatedTo( ChronoUnit.SECONDS );
Or if you for simplicity you may want to truncate to whole minutes if not rapidly creating such files.
Instant instant = Instant.now().truncatedTo( ChronoUnit.MINUTES );
You can generate a string in standard ISO 8601 format by calling toString.
String output = instant.toString();
2016-10-02T19:04:16Z
Stick with UTC
The Z on the end is short for Zulu and means UTC. As a programmer always, and as a user sometimes, you should think of UTC as the “One True Time” rather than “just another time zone”. You can prevent many problems and errors by sticking with UTC rather than any particular time zone.
Colons
Those colons are not allowed in the HFS Plus file system used by Mac OS X (macOS), iOS, watchOS, tvOS, and others including support in Darwin, Linux, Microsoft Windows.
Use ISO 8601 standard formats
The ISO 8601 standard provides for “basic” versions with a minimal number of separators along with the more commonly used “extended” format seen above. You can morph that string above to the “basic” version by simply deleting the hyphens and the colons.
String basic = instant.toString().replace( "-" , "" ).replace( ":" , "" );
20161002T190416Z
Insert that string into your file name as directed in the other Answers.
More elegant
If you find the calls to String::replace clunky, you can use a more elegant approach with more java.time classes.
The Instant class is a basic building-block class, not meant for fancy formatting. For that, we need the OffsetDateTime class.
Instant instant = Instant.now().truncatedTo( ChronoUnit.SECONDS );
OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC );
Now define and cache a DateTimeFormatter for the “basic” ISO 8601 format.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "uuuuMMdd'T'HHmmss" );
Use that formatter instance to generate a String. No more needing to replace characters in the String.
String output = odt.format( formatter );
You can also use this formatter to parse such strings.
OffsetDateTime odt = OffsetDateTime.parse( "20161002T190416Z" , formatter );
Zoned
If you decide to use a particular region’s wall-clock time rather than UTC, apply a time zone in a ZoneId to get a ZonedDateTime object. Similar to an OffsetDateTime but a time zone is an offset-from-UTC plus a set of rules for handling anomalies such as Daylight Saving Time (DST).
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );
Use the same formatter as above, or customize to your liking.
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 SimpleDateFormat and split to keep file extension:
private static String FILE = "D:\Report.pdf";
DateFormat df = new SimpleDateFormat("yyyyMMddhhmmss"); // add S if you need milliseconds
String filename = FILE.split(".")[0] + df.format(new Date()) + FILE.split(".")[1];
// filename = "D:\Report20150915152301.pdf"
UPDATE: if you are able to modify FILE variable, my suggestion will be:
private static String FILE_PATH = "D:\Report";
private static String FILE_EXTENSION = ".pdf";
DateFormat df = new SimpleDateFormat("yyyyMMddhhmmss"); // add S if you need milliseconds
String filename = FILE_PATH + df.format(new Date()) + "." + FILE_EXTENSION;
// filename = "D:\Report20150915152301.pdf"

You can do something like that
Define your file name pattern as below :
private static final String FILE = "D:\Report_{0}.pdf";
private static final String DATE_PATTERN = "yyyy-MM-dd:HH:mm:ss";
The {0} is a marker to be replaced by the following code
private String formatFileName(Date timeStamp) {
DateFormat dateFormatter = new SimpleDateFormat(DATE_PATTERN);
String dateStr = dateFormatter.format(timeStamp);
return MessageFormat.format(FILE, dateStr);
}
For further information over date format you can see there and MessageFormat there

Related

Confusions about Java's Date class and getTime() function

I am new to Java's Date class. When I try to use its getTime() function for calculating time difference, issues come out. For example, below is the code.
Date date = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
task = opt.get();
task.setEndDate(dateFormat.format(date));
Date startDate = null;
try {
startDate = dateFormat.parse(task.getStartDate());
} catch (ParseException e) {
System.out.println("date parsing error...");
startDate = date;
}
System.out.printf("Start date is: %s", task.getStartDate());
System.out.printf("Start date is: %d", startDate.getTime());
System.out.printf("End date is: %s", task.getEndDate());
System.out.printf("End date is: %d", date.getTime());
long diff = date.getTime() - startDate.getTime() - 43200000;
System.out.printf("Time difference is: %d", diff);
int secNum = (int)(diff / 1000);
String timeCost = String.valueOf(secNum);
System.out.println("Time cost(sec) is:");
System.out.println(timeCost);
task.setTimeCost(timeCost);
The outputs are:
Start date is: 2020-04-15 01:46:17
Start date is: 1586929577000
End date is: 2020-04-15 01:46:35
End date is: 1586972795461
Time difference is: 18461
Time cost(sec) is:18
As you might notice, there is 12 hours(43200000 ms) offset between the calculated difference and the real difference through "date.getTime() - startDate.getTime()".
I don't know what's going on.
Does anyone have an idea and correct me ?
It seems you are storing the date/time as a string in your task object, and converting between Date and String using the format "yyyy-MM-dd hh:mm:ss". I believe lower-case h means you are using a 12-hour clock, but you do not include an AM/PM indicator in your format string.
I'm guessing you ran the code at 1:46 PM to produce the sample output.
You have "2020-04-15 01:46:17" stored as your start date. When you convert that back to a date, the formatter doesn't know whether it is an AM time or PM time. I guess that it defaults to AM.
The Date object, however, knows that it was initialized with a PM time. Therefore, when you subtract the two, you get over 12 hours difference, because it is subtracting 1:46:17 AM from 1:46:35 PM.
A simple recommendation would be to add an AM/PM indicator to your date format, or use a 24-hour clock (upper-case H in the format string).
An even better recommendation would be to store dates as dates, not as strings! Convert them to strings when you want to display them.
You are using hh which is a 12-hour hour format, hence 20:00 becomes 08:00. You should use HH which is a 24-hour format. The below illustrates the difference.
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
Date date = new Date(1586973600000L);
System.out.println(date);
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String fd1 = df.format(date);
System.out.println(fd1);
System.out.println(df.parse(fd1));
df.applyPattern("yyyy-MM-dd HH:mm:ss");
String fd2 = df.format(date);
System.out.println(fd2);
System.out.println(df.parse(fd2));
Also, java.util.Date is old, buggy and generally avoided for some time now. You might want to switch to java.time instead.
java.time
I am new to Java's Date class.
Stop! Backup, rewind.
Both java.util.Date and java.sql.Date classes are terrible, deeply flawed, and quite frustrating. Never use these classes.
These classes were shipped in the earliest versions of Java. Supplanted years ago by the modern java.time classes defined in JSR 310.
Date date = new Date();
To capture the current moment in UTC, use Instant.now. Uses a resolution finer than the milliseconds used in the java.util.Date class it replaced.
Instant instant = Instant.now() ; // Capture the current moment in UTC.
task.setEndDate(dateFormat.format(date));
Your Task class should hold a java.time object rather than a mere string.
class Task {
Instant start , stop ;
…
}
Use smart objects rather than dumb strings throughout your Java codebase. Doing so ensures valid values, provides type-safety, and makes your code more self-documenting.
If your Task is like booking appointments in the future, where you want a certain time-of-day regardless of changes to the offset used by your time zone, then use LocalDateTime. This type represents only a date and time-of-day but lacks any concept of time zone or offset.
LocalDate ld = LocalDate.of( 2020 , Month.APRIL , 15 ) ;
Localtime lt = LocalTime.of( 15 , 30 ) ;
LocalDateTime ldt = LocalDateTime.of( ld , lt ) ;
When generating a calendar where you need a specific point on the timeline, then apply the relevant time zone.
ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z ) ;
The issue at stake here is the fact that politicians around the world have shown a predilection for changing the offset used by the time zone(s) of their jurisdiction. The politicians do so with surprising frequency. And they have done so with little or no forewarning.
When exchanging date-time values with other systems textually, then use ISO 8601 formats. These formats are used by default in java.time when parsing/generating text. And for presentation to users, produce automatically localized strings using DateTimeFormatter.
new SimpleDateFormat("yyyy-MM-dd hh:mm:ss")
This format is incorrect if you are trying to record moments, specific points on the timeline. You must include an indication of time zone and/or offset-from-UTC to track a moment.
For moments, use the ISO 8601 formats mentioned above. Used by default, so no need to specify a formatting pattern.
String input = "2020-01-23T01:23:45.123456789Z" ;
Instant instant = Instant.parse( input ) ;
Adjust from UTC into the wall-clock time used by the people of a particular region (a time zone).
ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;
Generate localized text.
Locale locale = Locale.CANADA_FRENCH ;
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.FULL ).withLocale( locale ) ;
String output = zdt.format( f ) ;
See this code run live at IdeOne.com.
zdt.toString(): 2020-01-22T20:23:45.123456789-05:00[America/Montreal]
output: mercredi 22 janvier 2020 à 20 h 23 min 45 s heure normale de l’Est
long diff = date.getTime() - startDate.getTime() - 43200000;
No need to do the math yourself. We have a class for that: Duration.
Duration d = Duration.between( start , stop ) ;
If you want a count of whole seconds across the entire span of time, call Duration::toSeconds.
long seconds = d.toSeconds() ; // Entire duration in terms of whole seconds.
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.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
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. Hibernate 5 & JPA 2.2 support java.time.
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.

formatted string to date conversion without changing format in java

I have formatted date in the form of string and i want it in date format without changing formatted pattern
here is my code
Date currDate = new Date();//Fri Oct 31 03:48:24 PDT 2014
String pattern = "yyyy-MM-dd hh:mm:ss";
SimpleDateFormat formatter;
formatter = new SimpleDateFormat(pattern);
String formattedDate= formatter.format(currDate);//2014-10-31 04:23:42
here am getting in "yyyy-MM-dd hh:mm:ss" format and the same format i want it in date.
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
Date paidDate = sdf.parse(formattedDate);
System.out.println(pattern + " " + paidDate);//Fri Oct 31 03:48:24 PDT 2014
but i am getting result as Fri Oct 31 03:48:24 PDT 2014, so pls help me to get result as 2014-10-31 04:23:42 in date format
If I understood your problem correctly:
System.out.println(pattern + " " + sdf.format(paidDate);
You seem to be under the mistaken impression that a Date object somehow encodes format of the original date. It doesn't.
So ... when you do this:
Date paidDate = sdf.parse(formattedDate);
it does not "remember" original format of the text form of the date in paidDate. And it cannot. If you want to print / unparse a Date in any format than the default one, you should use a DateFormat and call its format method. Calling toString() will just give you the date in the default format.
Try this.
System.out.println(formatter.format(paidDate));
tl;dr
Do not conflate a date-time object with a string representing its value. A date-time object has no “format”.
ZonedDateTime.now( // Instantiate a `ZonedDateTime` object capturing the current moment.
ZoneId.of( "Africa/Tunis" ) // Assign this time zone through which we see the wall-clock time used by the people of this particular region.
).format( // Generate a string representing the value of this `ZonedDateTime` object.
DateTimeFormatter.ofPattern( "uuuu-MM-dd HH:mm:ss" ) // Define a formatting pattern to match your desire.
)
2018-03-10 07:36:23
Calling ZonedDateTime::toString generates a string in standard ISO 8601 format.
2018-03-10T07:36:23.595362+01:00[Africa/Tunis]
Date-time object has no “format”
You are confusing a date-time object in Java, or a date-time value stored in a database, with a textual representation. You can generate a string from a date-time object (or database value), but that string is separate and distinct from the value it represents. Do not conflate a string with its generating creator.
java.time
Avoid using the troublesome old date-time classes such as Date, Calendar, and SimpleDateFormat. Instead, use Instant, ZonedDateTime, and DateTimeFormatter classes, respectively.
If you have an input string such as 2014-10-31 04:23:42, replace the SPACE in the middle with a T to comply with ISO 8601 standard format. The java.time classes use ISO 8601 formats by default when parsing/generating strings.
String input = "2014-10-31 04:23:42".replace( " " , "T" ) ;
That input lacks any indicator of time zone or offset-from-UTC. So parse as a LocalDateTime which purposely lacks any concept of zone/offset.
LocalDateTime ldt = LocalDateTime.parse( input ) ;
ldt.toString(): 2014-10-31T04:23:42
A LocalDateTime does not represent a moment, is not a point on the timeline. To determine an actual moment, you must supply the context of a zone or offset.
ZoneId z = ZoneId.of( "Pacific/Auckland" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ; // Now we have an actual moment, a point on the timeline.
To capture the current moment in UTC, use Instant.
Instant instant = Instant.now() ;
Adjust into another zone.
ZonedDateTime zdt = instant.atZone( z ) ;
zdt.toString(): 2018-03-10T07:36:23.595362+01:00[Africa/Tunis]
I do not recommend generating strings lacking an indicator of zone/offset. But if you insist, use the built-in DateTimeFormatter and then replace the T in the middle with a SPACE to get your desired format.
String output = zdt.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME ).replace( "T" , " " ) ;
2018-03-10 07:36:23.595362
If you really do not want the fractional second, then define your own formatting pattern.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-MM-dd HH:mm:ss" ) ;
String output = zdt.format( f ) ;
2018-03-10 07:36:23
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.

Android: How to Format Date and Time Strings correctly?

How should I correctly format Date and Time Strings for the Android platform?
Here is some code:
String path = getFilesDir().getPath();
String filePath = path + "/somefile.xml";
File file = new File(filePath);
Date lastModDate = new Date(file.lastModified());
String filelastModDate = "Updated: " + lastModDate.toString();
You can format it various way...
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("h:mm a");
String currentTime = sdf.format(date);
Here you can put other format like
k:mm
h:mm
h:mm dd/MM/yyyy
etc.....
check this.... http://developer.android.com/reference/java/text/SimpleDateFormat.html
Thanks #receme I solved it. like this:
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("h:mm a",Locale.getDefault());
String currentTime = sdf.format(date);
Log.i(LOGTAG,"Current Time: " + currentTime);
tl;dr
Instant.ofEpochMilli( // Parse milliseconds count to a moment in UTC.
file.lastModified() // A count of milliseconds since the epoch reference of first moment of 1970 in UTC, 1970-01-01T00:00:00Z.
) // Returns a `Instant` object.
.atZone( // Adjust from UTC to some time zone. Same moment, same point on the timeline, different wall-clock time.
ZoneId.of( "Africa/Tunis" )
) // Returns a `ZonedDateTime` object.
.format( // Generate a `String`.
DateTimeFormatter
.ofLocalizedDateTime( FormatStyle.FULL ) // Specify how long or abbreviated.
.withLocale( Locale.JAPAN ) // Specify a `Local` to determine human language and cultural norms used in localizing.
) // Returns a `String`.
java.time
The modern approach uses the java.time classes.
The File.lastModified method returns a count of milliseconds since the epoch reference of first moment of 1970 in UTC, 1970-01-01T00:00:00Z.
long millisSinceEpoch = file.lastModified() ;
Parse that number as a modern java.time object.
Instant instant = Instant.ofEpochMilli( millisSinceEpoch ) ;
Generate a String to represent that values using standard ISO 8601 format.
String output = instant.toString() ; // Generate a `String` in standard ISO 8601 format.
2018-07-16T22:40:39.937Z
To view the same moment through the lens of the wall-clock time used by the people of a particular region (a time zone), apply a ZoneId to get a ZonedDateTime.
ZoneId z = ZoneId.of( "Pacific/Auckland" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;
2018-07-17T10:40:39.937+12:00[Pacific/Auckland]
Let java.time automatically localize. To localize, specify:
FormatStyle to determine how long or abbreviated should the string be.
Locale to determine:
The human language for translation of name of day, name of month, and such.
The cultural norms deciding issues of abbreviation, capitalization, punctuation, separators, and such.
Example:
Locale l = Locale.CANADA_FRENCH ;
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.FULL ).withLocale( l );
String output = zdt.format( f );
mardi 17 juillet 2018 à 10:40:39 heure normale de la Nouvelle-Zélande
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.
I would like to add my share here.
Note that the user can set his preferred format in the settings. Example on how to retrieve:
static DateFormat getUserDateFormat(Context context) {
if (mUserDateFormat == null)
mUserDateFormat = android.text.format.DateFormat.getDateFormat(context.getApplicationContext());
return mUserDateFormat;
}
See also ...getTimeFormat
You then have a java DateFormat to use with above mentioned examples.
Furthermore, Android contains it's own TextFormat class, look here: http://developer.android.com/reference/android/text/format/package-summary.html
This may look like:
static String getAppExpiredString() {
String date = android.text.format.DateFormat.getDateFormat(getAppContext()).format(App_Main.APP_RUN_TILL.getTime());
return getAppContext().getString(R.string.app_expired) + " " + date + ".";
}
Update: The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
Joda-Time
Install third-party library, Joda-Time.
By default, Joda-Time outputs strings in ISO 8601 format. That format is intuitively understandable by virtually anybody worldwide.
Search StackOverflow.com for many more examples.
// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// import org.joda.time.*;
DateTime now = new DateTime();
System.out.println( now );
When run…
2013-12-05T19:55:43.897-08:00
Though, The question is very old, but it may help one who wants it Kotlin version of this answer. Here I take a empty file name DateUtil and create a function called getDateString() which has 3 arguments.
1st argument : Your input date
2nd argument : Your input date pattern
3rd argument : Your wanted date pattern
DateUtil.kt
object DatePattern {
const val YEAR_MONTH_DAY = "yyyy-MM-dd"
const val DAY_MONTH_YEAR = "dd-MM-yyyy"
const val RFC3339 = "yyyy-MM-dd'T'HH:mm:ss'Z'"
}
fun getDateString(date: String, inputDatePattern: String, outputDatePattern: String): String {
return try {
val inputFormat = SimpleDateFormat(inputDatePattern, getDefault())
val outputFormat = SimpleDateFormat(outputDatePattern, getDefault())
outputFormat.format(inputFormat.parse(date))
} catch (e: Exception) {
""
}
}
And now use this method in your activity/fuction/dataSourse Mapper to get Date in String format like this
getDate("2022-01-18T14:41:52Z", RFC3339, DAY_MONTH_YEAR)
and output will be like this
18-01-2022

Conversion of string with AM/PM date-time, from Oracle database

I have the timestamp in form of 03-AUG-12 08.15.00.000000000 PM -05:00
I am unable to get a String representation in form on yyyy-MM-dd HH:mm:ss.
Here is my code :
public static void convert() {
String oldstring = "03-AUG-12 08.15.00.000000000 PM -05:00";
Date date = null;
try {
date = new SimpleDateFormat("dd-MMM-yy HH.mm.ss.S aa").parse(oldstring);
}
catch (ParseException e) {
e.printStackTrace();
}
String newstring = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
System.out.println(newstring);
}
Basically it is a timestamp with timezone format from the Oracle database.
You can't use SimpleDateFormat to parse such a string, at least not without some limitations:
A time zone designator like -05:00 (according to ISO 8601) is not supported until Java 7. With Java 7 you can use the XXX pattern to parse it.
To parse the month name correctly, you should specify that you require an English locale.
The pattern for milliseconds (S) parses an unlimited number of digits. If your string contains "08.15.00.100000000", SimpleDateFormat would parse this as 8:15:00 and 100000000ms, adding almost 28 hours to the expected value. If you are sure that the value is always 0, you can ignore this problem.
If you can accept the last issue and use Java 7, you should be using something like this:
new SimpleDateFormat("dd-MMM-yy hh.mm.ss.S aa XXX", Locale.ENGLISH)
Change this line like this:
date = new SimpleDateFormat("dd-MMM-yy hh.mm.ss.S aa").parse(oldstring);
You need to use the lowercase h which parses the AM/PM hours 1-12.
tl;dr
DateTimeFormatter f = new DateTimeFormatterBuilder ().parseCaseInsensitive ().appendPattern ( "dd-MMM-yy hh.mm.ss.SSSSSSSSS a ZZZZZ" ).toFormatter ().withLocale ( Locale.US );
OffsetDateTime odt = OffsetDateTime.parse ( "03-AUG-12 08.15.00.000000000 PM -05:00" , f );
Objects, not strings
You mentioned Oracle. When retrieving data from a database, use objects rather than strings. Ask your ResultSet for a java.sql.Timestamp object.
java.sql.Timestamp ts = myResultSet.getTimestamp( … );
Convert from the troublesome old date-time class to the modern java.time type. Look to new methods added on the old classes to facilitate conversion to/from java.time.
Instant instant = ts.toInstant();
Or preferably, if using JDBC 4.2 or later, and using Java 8 or later, you may be able to retrieve an java.time.Instant via the ResultSet::getObject method.
But if you must parse a string, read on.
Avoid old date-time classes
The old date-time classes bundled with the earliest versions of Java are troublesome and confusing. Now supplanted by the java.time classes.
Nanoseconds
That bunch of zeros must represent a fraction of a second with nanosecond resolution, up to nine digits of a decimal fraction. The old date-time classes can handle only milliseconds, but fortunately the modern java.time classes can indeed handle a resolution up to nanoseconds.
Using java.time
Define a formatting pattern to parse the given input. By the way, your data’s format is less than optimal; in the future, use ISO 8601 standard formats for strings that represent date-time values.
We use a “builder” in order to specify case-insensitive parsing. Proper abbreviation for a name of month in English is initial-cap, Aug, but your input uses all-caps.
String pattern = "dd-MMM-yy hh.mm.ss.SSSSSSSSS a ZZZZZ";
DateTimeFormatterBuilder fb = new DateTimeFormatterBuilder ().parseCaseInsensitive ().appendPattern ( pattern );
Tell the builder to instantiate our formatter. The Locale to determines (a) the human language for translation of name of day, name of month, and such, and (b) the cultural norms deciding issues of abbreviation, capitalization, punctuation, and such.
Locale l = Locale.US;
DateTimeFormatter f = fb.toFormatter ().withLocale ( l );
Finally, parse the string as an OffsetDateTime object.
String input = "03-AUG-12 08.15.00.000000000 PM -05:00";
OffsetDateTime odt = OffsetDateTime.parse ( input , f );
Dump to console. Note how our 8 PM is transformed into the 24-hour clock value of 20 hours.
System.out.println ( "input: " + input + " | odt.toString(): " + odt );
input: 03-AUG-12 08.15.00.000000000 PM -05:00 | odt.toString(): 2012-08-03T20:15-05:00
A time zone is an offset-from-UTC plus a set of rules for handling anomalies such as Daylight Saving Time (DST). If desired, apply a ZoneId to get a ZonedDateTime.
ZoneId z = ZoneId.of( “America/Montreal” );
ZonedDateTime zdt = odt.atZoneSameInstant( z );
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. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

How can I parse UTC date/time (String) into something more readable?

I have a String of a date and time like this: 2011-04-15T20:08:18Z. I don't know much about date/time formats, but I think, and correct me if I'm wrong, that's its UTC format.
My question: what's the easiest way to parse this to a more normal format, in Java?
tl;dr
String output =
Instant.parse ( "2011-04-15T20:08:18Z" )
.atZone ( ZoneId.of ( "America/Montreal" ) )
.format (
DateTimeFormatter.ofLocalizedDateTime ( FormatStyle.FULL )
.withLocale ( Locale.CANADA_FRENCH )
)
;
vendredi 15 avril 2011 16 h 08 EDT
Details
The answer by Josh Pinter is correct, but could be even simpler.
java.time
In Java 8 and later, the bundled java.util.Date/Calendar classes are supplanted by the java.time framework defined by JSR 310. Those classes are inspired by Joda-Time but are entirely re-architected.
The java.time framework is the official successor to Joda-Time. The creators of Joda-Time have advised we should migrate to java.time as soon as is convenient. Joda-Time continues to be updated and tweaked, but further innovation will be done only in java.time and its extensions in the ThreeTen-Extra project.
The bulk of java.time functionality has been back-ported to Java 6 & 7 in the ThreeTen-Backport project, and further adapted to Android in ThreeTenABP project.
The equivalent for the Joda-Time code above is quite similar. Concepts are similar. And like Joda-Time, the java.time classes by default use ISO 8601 formats when parsing/generating textual representations of date-time values.
An Instant is a moment on the timeline in UTC with a resolution of nanoseconds (versus milliseconds used by Joda-Time & java.util.Date).
Instant instant = Instant.parse( "2011-04-15T20:08:18Z" );
Apply a time zone (ZoneId) to get a ZonedDateTime.
ZoneId zoneId = ZoneId.of( "Asia/Kolkata" );
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );
Adjust into yet another time zone.
ZoneId zoneId_NewYork = ZoneId.of( "America/New_York" );
ZonedDateTime zdt_NewYork = zdt.withZoneSameInstant( zoneId_NewYork );
To create strings in other formats beyond those of the toString methods, use the java.time.format classes. You can specify your own formatting pattern or let java.time localize automatically. Specify a Locale for (a) the human language used in translation of name of month/day-of-week, and (b) cultural norms for period-versus-comma, order of the parts, and such.
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.FULL );
formatter = formatter.withLocale( Locale.US );
String output = zdt_NewYork.format( formatter );
Friday, April 15, 2011 4:08:18 PM EDT
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.
Joda-Time
UPDATE: The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes. This section left intact for history.
Pass String To Constructor
Joda-Time can take that string directly. Simply pass to a constructor on the DateTime class.
Joda-Time understands the standard ISO 8601 format of date-times, and uses that format as its default.
Example Code
Here is example code in Joda-Time 2.3 running in Java 7 on a Mac.
I show how to pass the string to a DateTime constructor, in two ways: With and without a time zone. Specifying a time zone solves many problems people encounter in doing date-time work. If left unspecified, you get the default time zone which can bring surprises when placed into production.
I also show how specify no time zone offset (UTC/GMT) using the built-in constant DateTimeZone.UTC. That's what the Z on the end, short for Zulu time, means: No time zone offset (00:00).
// © 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.*;
// Default time zone.
DateTime dateTime = new DateTime( "2011-04-15T20:08:18Z" );
// Specified time zone.
DateTime dateTimeInKolkata = new DateTime( "2011-04-15T20:08:18Z", DateTimeZone.forID( "Asia/Kolkata" ) );
DateTime dateTimeInNewYork = new DateTime( "2011-04-15T20:08:18Z", DateTimeZone.forID( "America/New_York" ) );
// In UTC/GMT (no time zone offset).
DateTime dateTimeUtc = dateTimeInKolkata.toDateTime( DateTimeZone.UTC );
// Output in localized format.
DateTimeFormatter formatter = DateTimeFormat.shortDateTime().withLocale( Locale.US );
String output_US = formatter.print( dateTimeInNewYork );
Dump to console…
System.out.println("dateTime: " + dateTime );
System.out.println("dateTimeInKolkata: " + dateTimeInKolkata );
System.out.println("dateTimeInNewYork: " + dateTimeInNewYork );
System.out.println("dateTimeUtc: " + dateTimeUtc );
System.out.println("dateTime in US format: " + output_US );
When run…
dateTime: 2011-04-15T13:08:18.000-07:00
dateTimeInKolkata: 2011-04-16T01:38:18.000+05:30
dateTimeInNewYork: 2011-04-15T16:08:18.000-04:00
dateTimeUtc: 2011-04-15T20:08:18.000Z
dateTime in US format: 4/15/11 4:08 PM
Use JodaTime
I kept getting parsing errors using the other solutions with the Z at the end of the format.
Instead, I opted to leverage JodaTime's excellent parsing functionality and was able to do the following very easily:
String timestamp = "2011-04-15T20:08:18Z";
DateTime dateTime = ISODateTimeFormat.dateTimeParser().parseDateTime(timestamp);
This correctly recognizes the UTC timezone and allows you to then use JodaTime's extensive manipulation methods to get what you want out of it.
Hope this helps others.
Already has lot of answer but just wanted to update with java 8 in case any one faced issues while parsing string date.
Generally we face two problems with dates
Parsing String to Date
Display Date in desired string format
DateTimeFormatter class in Java 8 can be used for both of these purpose.
Below methods try to provide solution to these issues.
Method 1:
Convert your UTC string to Instant. Using Instant you can create Date for any time-zone by providing time-zone string and use DateTimeFormatter to format date for display as you wish.
String dateString = "2016-07-13T18:08:50.118Z";
String tz = "America/Mexico_City";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MMM d yyyy hh:mm a");
ZoneId zoneId = ZoneId.of(tz);
Instant instant = Instant.parse(dateString);
ZonedDateTime dateTimeInTz =ZonedDateTime.ofInstant(instant, zoneId);
System.out.println(dateTimeInTz.format(dtf));
Method 2:
Use DateTimeFormatter built in constants e.g ISO_INSTANT to parse string to LocalDate.
ISO_INSTANT can parse dates of pattern
yyyy-MM-dd'T'HH:mm:ssX e.g '2011-12-03T10:15:30Z'
LocalDate parsedDate
= LocalDate.parse(dateString, DateTimeFormatter.ISO_INSTANT);
DateTimeFormatter displayFormatter = DateTimeFormatter.ofPattern("yyyy MM dd");
System.out.println(parsedDate.format(displayFormatter));
Method 3:
If your date string has much precision of time e.g it captures fraction of seconds as well as in this case 2016-07-13T18:08:50.118Z then method 1 will work but method 2 will not work. If you try to parse it will throw DateTimeException Since ISO_INSTANT formatter will not be able to parse fraction of seconds as you can see from its pattern.
In this case you will have to create a custom DateTimeFormatter by providing date pattern as below.
LocalDate localDate
= LocalDate.parse(date, DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSX"));
Taken from a blog link written by me.
The Java 7 version of SimpleDateFormat supports ISO-8601 time zones using the uppercase letter X.
String string = "2011-04-15T20:08:18Z";
DateFormat iso8601 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
Date date = iso8601.parse(string);
If you're stuck with Java 6 or earlier, the answer recommending JodaTime is a safe bet.
You have to give the following format:
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Date parse = simpleDateFormat.parse( "2011-04-15T20:08:18Z" );
I had a parse error in Andrew White solution.
Adding the single quote around the Z solved the issue
DateFormat m_ISO8601Local = new SimpleDateFormat ("yyyy-MM-dd'T'HH:mm:ss'Z'");
the pattern in #khmarbaise answer worked for me, here's the utility method I extracted (note that the Z is omitted from the pattern string):
/**
* Converts an ISO-8601 formatted UTC timestamp.
*
* #return The parsed {#link Date}, or null.
*/
#Nullable
public static Date fromIsoUtcString(String isoUtcString) {
DateFormat isoUtcFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.getDefault());
isoUtcFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
try {
return isoUtcFormat.parse(isoUtcString);
} catch (ParseException e) {
e.printStackTrace();
return null;
}
}
For all the older versions of JDK (6 down) it may be useful.
Getting rid of trailing 'Z' and replacing it literally with 'UTC' timezone display name - then parsing the whole string using proper simple date formatter.
String timeZuluVal = "2011-04-15T20:08:18Z";
timeZuluVal = timeZuluVal.substring( 0, timeZuluVal.length() - 2 ); // strip 'Z';
timeZuluVal += " " + TimeZone.getTimeZone( "UTC" ).getDisplayName();
DateFormat simpleDateFormat = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ss zzzz" );
Date dateVal = simpleDateFormat.parse( timeZuluVal );
Joda Time
public static final String SERVER_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
public static DateTime getDateTimeFromUTC(String time) {
try {
DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(SERVER_TIME_FORMAT).withZoneUTC();
Calendar localTime = Calendar.getInstance();
DateTimeZone currentTimeZone = DateTimeZone.forTimeZone(localTime.getTimeZone());
return dateTimeFormatter.parseDateTime(time).toDateTime().withZone(currentTimeZone);
} catch (Exception e) {
return DateTime.now();
}
}

Categories