I need to replace SimpleDataFormat with Java 8 DateTimeFormatter. Below is the code with SimpleDateFormat.
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = sdf.parse(source);
Now I need to change it to DateTimeFormatter. I tried as below
LocalDateTime ld = LocalDateTime.now();
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
Date startdate = dtf.parse(dtf);
Now this is generating exception.
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate localDate = LocalDate.parse("2017-02-11", dtf);
System.out.println(localDate.toString());
if you want Date object from LocalDate,the following works
Date date = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
As #JonSkeet advised, If you're using Java 8 you should probably avoid java.util.Date altogether
If looking for equivalent of your sdf in DateTimeFormatter try DateTimeFormatter.ISO_LOCAL_DATEExplore the DateTimeFormatter class for more formats.
LocalDateTime time = LocalDateTime.now();
time.format(DateTimeFormatter.ISO_LOCAL_DATE);
Use LocalDate instead of LocalDateTime if intrested in Date only.
tl;dr
java.util.Date.from(
LocalDate.parse( "2017-01-23" )
.atStartOfDay( ZoneId.of( "America/Montreal" ) )
.toInstant()
)
No need of formatting pattern
No formatting pattern needed. Your input string happens to be in standard ISO 8601 format. These standard formats are used by default in the java.time classes for parsing and generating strings.
LocalDate
Use LocalDate for a date-only value, without time-of-day and without time zone.
LocalDate ld = LocalDate.parse( "2017-01-23" );
ZonedDateTime
If you want a date-time, let java.time determine the first moment of the day. Do not assume that first moment is 00:00:00.
Determining first moment of the day requires a time zone. The date varies around the globe by zone.
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ld.atStartOfDay( z );
If you want to perceive that moment through the lens of UTC, extract an Instant object.
Instant instant = zdt.toInstant();
The Instant is equivalent to the old legacy class java.util.Date. Both represent a moment on the timeline in UTC. The modern class has a finer resolution, nanoseconds rather than milliseconds.
Avoid java.util.Date
As others mentioned, you should stick with the modern java.time classes. But if you must, you can convert. Look to new methods added to the old classes.
java.util.Date d = java.util.Date.from( instant ) ;
One way of doing it would be -
LocalDateTime ld = LocalDateTime.now();
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
String date = ld.format(dtf);
I need your help in getting the proper format to insert the date and time informaiton which is retrieved from two different string variables from the database and to insert them (date and time) into Date and Time column in an another table. The date is retrieved from the agreement date column which is:
String agreement_date = "";
agreement_date=rs.getString("agr_date"); //format DD-MON-YYYY ex. 22-May-2014
And the time is retrieved from:
String frm_time = rs.getString("FRM_TIME"); //format HH:MI ex.7:20
So now I need to combine both columns into one variable and to insert them in database column called transaction_dt_time and its type is dateTime(format dd/MM/YYYY HH:MI:SS AM/PM), So how can I do that?
You can concatenate these strings into datetime string and convert to date using SimpleDateFormat for example
SimpleDateFormat format = new SimpleDateFormat("dd-MMM-yyyy HH:mm");
Date dateToInsert = format.parse(concatenatedDate);
I understand you are fetching the values in the resultset from a database. generally date and time are stored in database according to the datatype. Recommend to use a rs.getDate() and rs.getTime() to fetch these values instead of a String datatype.
Here is a sample code for your conversion
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateDemo {
public static void main(String[] args) {
try{
String date = "22-May-2015";
String time = "7:20";
String yourString = date+ " "+ time;
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy HH:mm");
Date parsedDate = dateFormat.parse(yourString);
Timestamp timestamp = new java.sql.Timestamp(parsedDate.getTime());
System.out.println(timestamp);
}catch(Exception e){
e.printStackTrace();
//this generic but you can control another types of exception
// look the origin of excption
}
}
}
Hope this helps!
use a simpledateformat() for the time, is your time 24hours? how do we know if it's AM or PM?
SimpleDateFormat sdfTime = new SimpleDateFormat("HH:MI:SS"); //AM/PM?
String strTime = sdfTime.format(frm_time);
final_date = agreement_date.replaceAll("-","/");
String FinalDate = final_date + strTime;
You may use JPA 2.1 and its AttributeConverter interface
java.time
The other answers use legacy date-time classes, now supplanted by the java.time framework built into Java 8 and later.
First, parse the date portion.
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern( "mm-DD-yyyy" );
LocalDate localDate = LocalDate.parse( "22-May-2014" , dateFormatter );
Second, parse the time portion.
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern( "h:m" );
LocalTime localTime = LocalTime.parse( "7:20" , dateFormatter );
Third, determine the time zone in which this value has meaning. Is this a Montréal time, a Paris time, or a Kolkata time?
ZoneId zoneId = ZoneId.of( "America/Montreal" );
Combine into a ZonedDateTime.
ZonedDateTime zdt = ZonedDateTime.of( localDate , localTime , zoneId );
You may be able to pass this ZonedDateTime to your database via the setObject method on a PreparedStatement with a JDBC 4.2 compliant driver. But if not, convert into the old java.sql.Timestamp type. That old class has a new method to facilitate conversion, which takes an Instant object. An Instant is a moment on the timeline in UTC with a resolution of nanoseconds. We can extract an Instant from our ZonedDateTime.
Instant instant = zdt.toInstant();
java.sql.Timestamp ts = java.sql.Timestamp.from( instant );
On your PreparedStatement, call setTimestamp.
I have a requirement where i have to store different date and time with time zones.
I have used ZonedDateTime of java 8 .
ZoneId zoneId = ZoneId.of("US/Eastern");
ZonedDateTime zt = ZonedDateTime.now(zoneId);
System.out.println(zt.toString());
My problem is I want to store this in java.util.Date format.
I used DateTimeFormatter
DateTimeFormatter dtf=DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ");
dtf.format(zt);
Until here it works fine this gives me the required date in string format now when i try to convert this to java.util.Date using simple date format
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
System.out.println(sdf.parse(dtf.format(zt)));
I get output as Sat Mar 12 00:44:10 IST 2016 but i want output as 2016-03-11T14:14:10-05:00 in java.util.Date type. Can somebody suggest where am i going wrong?
You are using a wrong way this is the corrected code
sdf.format(sdf.parse(val)) this the right way.
ZoneId zoneId = ZoneId.of("US/Eastern");
ZonedDateTime zt = ZonedDateTime.now(zoneId);
System.out.println(zt.toString());
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ");
String val = dtf.format(zt);
System.out.println(val);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
//String dateStr = zt.format(sdf);
System.out.println(sdf.format(sdf.parse(val)));
ZonedDateTime > Instant > Date
Best to avoid the old date-time classes including java.util.Date. But if you must, you can convert. Call the new from method on the old java.util.Date class.
For that you need an Instant a moment on the timeline in UTC.
Instant instant = myZonedDateTime.toInstant();
java.util.Date juDate = java.util.Date.from( instant );
To go the other direction:
Instant instant = juDate.toInstant();
Can anybody tell me how to convert date to epoch in java.
e.g. 2011-05-01 13:12:20 IST or 2011-05-01 14:11:10 PST to epoch.
I am able to convert using 2011-05-01 13:12:20 format but when I use timezone alongwith it I am not getting correct result.
Construct a SimpleDateFormat with a string pattern that matches the date format you have. The "Date and Time" section and the "Examples" section should give you more than enough help on how to construct your date format string
Then simply do the following to get your date (with the appropriate date format string).
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date date = sdf.parse("15/01/2012");
java.time
Using the java.time classes.
String input = "2011-05-01 13:12:20".replace( " " , "T" );
LocalDateTime ldt = LocalDateTime.parse( input );
ZonedDateTime zdt = ldt.atZone( ZoneId.of( "Asia/Kolkata" ) );
If by “epoch”, you mean a count of whole seconds or milliseconds from the epoch reference date of first moment of 1970 in UTC (often referred to as Unix Time), then interrogate the ZonedDateTime object via an extracted Instant object.
long wholeSecondsSinceEpoch = zdt.toInstant().getEpochSecond();
long millisecondsSinceEpoch = zdt.toInstant().toEpochMilli();
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());