Is it possible or are there any method which is automatically convert this type of string to the date object ?
String is = yyyy_mm_ddThh-mm-ss
I need the convert this string to date object because i have to compare with real time. The substring or split may work but i just want to learn is there any special thing or not
EDIT :
From cause of T in the middle of, simpleDateFormat not working correctly from my side.
SOLVED :
I forget to put ' before and after the T
SimpleDateFormat("yyyy_mm_dd'T'hh-mm-ss");
You need to skip T with single quotation 'T'. Also note that, small 'm' is the format of minute. Use capital 'M' for month format. Try,
DateFormat df=new SimpleDateFormat("yyyy_MM_dd'T'hh-mm-ss");
System.out.println(df.format(new Date()));
For details, read this documentation of SimpleDateFormat
You need to parse the String with the date format like this:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy_MM_dd'T'hh-mm-ss");
Date date;
try {
date = sdf.parse(sdf1.format(dateX) + " " + time);
} catch (ParseException e) {
e.printStackTrace();
}
Joda-Time
Joda-Time provides built-in formatters for a variety of such ISO 8601 formats. So you need not even bother with creating that format string.
See this class:
http://www.joda.org/joda-time/apidocs/org/joda/time/format/ISODateTimeFormat.html
Update
I learned you don't even need the formatter with Joda-Time 2.3.
Your string is almost in ISO 8601 format. Replace those underscores with hyphens.
The constructor of DateTime accepts a string in ISO 8601 format.
// © 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.*;
DateTime dateTime = new DateTime( "2001-02-03T04:05:06", DateTimeZone.UTC );
System.out.println( "dateTime: " + dateTime.toString() );
When run…
dateTime: 2001-02-03T04:05:06.000Z
Time Zones
By the way, your question fails to address the issue of time zones. My example code assumes you meant UTC/GMT (no time zone offset). If you meant otherwise, you should say so. Date-time work should always be explicit about time zones rather than rely on defaults.
Related
Using java I try to format the current date with the timezone using SimpleDateFormat
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss:SSSZ");
sdf.format(new Date());
This give me as results :
2021-04-28T13:45:52:308+0300
I want to get the timezone format with the "Z" instead of "+"
wanted results : "2021-04-28T13:45:52:308Z03:00"
I writed the date output in a file log that will be parsed by telegraf plugin writed in Go language that expect date with time zone with the following format : json_time_format = "2006-01-02T15:04:05Z07:00"
Is there a pattern allows that ?
You misunderstood. 2006-01-02T15:04:05Z07:00 does not mean that you should have a Z instead of a plus (what would you put instead of a minus, then?) This way of specifying a date and time format approximates how the fixed example date and time of Mon Jan 2 15:04:05 MST 2006 would be formatted, but it’s only an approximation. Specifically when it comes to the offset from UTC, the format requires Z when the offset is zero and +hh:mm or -hh:mm when it is non-zero. In accordance with ISO 8601 and RFC-3339. You see immediately that just giving the correct formatting of the example date and time, 2006-01-02T15:04:05-07:00, would not tell the reader that offset 0 should be given as Z. Therefore this particular requirement is specified as Z07:00 in the format. According to Format a time or date [complete guide] (link at the bottom), your particular format, 2006-01-02T15:04:05-0700, denotes ISO 8601 or RFC-3339.
So all you need to do is use DateTimeFormat.ISO_OFFSET_DATE_TIME or OffsetDateTime.toString().
A couple of examples follow.
String result = OffsetDateTime.now().toString();
System.out.println(result);
Output when running on Java 8 in my time zone just now:
2021-04-29T17:00:55.716+02:00
If the fraction of second is not allowed — well, according to ISO 8601 it is optional, so it should be, but if not:
String result = OffsetDateTime.now().truncatedTo(ChronoUnit.SECONDS)
.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME);
2021-04-29T17:00:55+02:00
If you have got an old-fashioned Date object from legacy code, convert it before formatting:
Date oldfashionedDate = new Date();
String result = oldfashionedDate.toInstant()
.atZone(ZoneId.systemDefault())
.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME);
2021-04-29T17:00:55.739+02:00
Links
Oracle tutorial: Date Time explaining how to use java.time.
Wikipedia article: ISO 8601
Format a time or date [complete guide]
Z is for "Zulu time" or zero hour offset, i.e. UTC +0:00
It's not correct to use it if you're not in that timezone. How would you know whether you're before or after the meridian if you replace it with Z? Given Z03:00 do you parse it as +03:00 or -03:00?
Since Z means Zulu time offset you can't use it as part of the format string but you can of course add Z as a hardcoded character
ZonedDateTime now = ZonedDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'Z");
System.out.println(formatter.format(now));
2021-04-29T15:34:17.661Z+0200
Then if you don't want the '+' you can remove it afterwards but it is not clear on what to do whit a '-' so I left it out of the answer.
Semantically as mentioned above its quite wrong.But you can achieve this with some custom parsing logic.
I will assume 2 things:
The date will not contain timezones with negative differences
The date format will not change
In any other cases, this is not safe!!
But here you go:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss:SSSZ");
String originalDateString = sdf.format(new Date());
String[] parts = originalDateString.split("\\+");
StringBuilder sb = new StringBuilder(parts[1]);
sb.insert(2, ':');
parts[1] = sb.toString();
String result = String.join("Z",parts);
System.out.println(result);
This will create from this:
2021-04-29T14:12:21:376+0000
This:
2021-04-29T14:12:21:376Z00:00
I have been parsing dates in the below formats. I maintain an array of these formats and parse every date string in all these formats.
The code I used was -
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat);
simpleDateFormat.setTimeZone(timeZone); //timeZone is a java.util.TimeZone object
Date date = simpleDateFormat.parse(dateString);
Now I want to parse yyyy-MM-dd'T'HH:mm:ss.SSSSSSXXX format as well but using SimpleDateFormat the 6 digit microseconds are not considered. So I looked into java.time package.
To parse yyyy-MM-dd'T'HH:mm:ss.SSSSSSXXX formats I will be needing OffsetDateTime class and for other formats, I need ZonedDateTime class. The format will be set in DateTimeFormatter class.
Is there a way to use a single class like SimpleDateFormat to pass all the formats?
Since your Java 8 doesn’t behave as would be reasonably expected, I suggest that a workaround is trying to parse without zone first. If a zone or an offset is parsed from the string, this will be used. If the parsing without zone fails, try with a zone. The following method does that:
private static void parseAndPrint(String formatPattern, String dateTimeString) {
// Try parsing without zone first
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(formatPattern);
Instant parsedInstant;
try {
parsedInstant = formatter.parse(dateTimeString, Instant::from);
} catch (DateTimeParseException dtpe) {
// Try parsing with zone
ZoneId defaultZone = ZoneId.of("Asia/Calcutta");
formatter = formatter.withZone(defaultZone);
parsedInstant = formatter.parse(dateTimeString, Instant::from);
}
System.out.println("Parsed instant: " + parsedInstant);
}
Let’s try it:
parseAndPrint("yyyy-MM-dd'T'HH:mm:ss.SSSSSSXXX", "2018-10-22T02:17:58.717853Z");
parseAndPrint("yyyy-MM-dd'T'HH:mm:ss.SSSSSS", "2018-10-22T02:17:58.717853");
parseAndPrint("EEE MMM d HH:mm:ss zzz yyyy", "Mon Oct 22 02:17:58 CEST 2018");
Output on Java 8 is:
Parsed instant: 2018-10-22T02:17:58.717853Z
Parsed instant: 2018-10-21T20:47:58.717853Z
Parsed instant: 2018-10-22T00:17:58Z
The first example has an offset in the string and the last a time zone abbreviation in the string, and in both cases are these respected: the instant printed has adjusted the time into UTC (since an Instant always prints in UTC, its toString method makes sure). The middle example has got neither offset nor time zone in the string, so uses the default time zone of Asia/Calcutta specified in the method.
That said, parsing a three or four letter time zone abbreviation like CEST is a dangerous and discouraged practice since the abbreviations are often ambiguous. I included the example for demonstration only.
Is there a way to use a single class…?
I have used Instant for all cases, so yes there is a way to use just one class. The limitation is that you do not know afterward whether any time zone or offset was in the string nor what it was. You didn’t know when you were using SimpleDateFormat and Date either, so I figured it was OK?
A bug in Java 8?
The results from your demonstration on REX tester are disappointing and wrong and do not agree with the results I got on Java 11. It seems to me that you have been hit by a bug in Java 8, possibly this one: Parsing with DateTimeFormatter.withZone does not behave as described in javadocs.
Hi so I do understand there are many threads out here regarding this and ive been through many of them I'm not able to grasp the whole date format thing so here I am seeking your help :)
I've got a json object giving me this date "2014-01-10T02:01:42.657Z" and I have no idea what sort of format that is. I do know its a datetime from mssql database and I wish to parse this in java for which I'm using this code.
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date result = null;
try {
result = df.parse(last_active);
} catch (ParseException e) {
Log.i("Date Parser problem (Friend.java): ", e.toString());
e.printStackTrace();
}
Log.i("Date: ", result.toString());
I do understand that the "yyyy-MM-dd HH:mm:ss" is the wrong format to parse this date with but I am not able to find the right type of format string to format the following date.
"2014-01-10T02:01:42.657Z"
I appreciate your help :)
Thank you
This is simply a standard ISO-formatted date. The T in the middle is simply a separator, and the Z at the end means "UTC".
To parse it, simply use yyyy-MM-dd'T'HH:mm:ss.SSSX as the pattern.
Try this
SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
ISO 8601
That string is in standard format, as defined by ISO 8601. In various protocols, this format is gradually replacing the silly formats of yesteryear such as Sun, 06 Nov 1994 08:49:37 GMT.
Avoid java.util.Date/Calendar
The bundled classes java.util.Date and .Calendar are notoriously troublesome. Avoid them. With the arrival of the java.time package in Java 8, they are practically deprecated. If you cannot go to Java 8, use Joda-Time (which inspired java.time).
Joda-Time
The Joda-Time library (third-party, open-source, free-of-cost) uses ISO 8601 for its defaults. So the Joda-Time class DateTime automatically parses such strings.
DateTime dateTime = new DateTime( "2014-01-10T02:01:42.657Z" );
Dump to console…
System.out.println( "dateTime: " + dateTime );
When run…
dateTime: 2014-01-09T18:01:42.657-08:00
Time Zone
Notice Joda-Time applied my JVM’s default time zone thereby adjusting the time appropriately. If you wish to keep the DateTime object in UTC, pass a DateTimeZone object in that constructor.
DateTime dateTime = new DateTime( "2014-01-10T02:01:42.657Z", DateTimeZone.UTC );
When run…
dateTime: 2014-01-10T02:01:42.657Z
java.time
The java.time package also uses ISO 8601 for its defaults, and automatically parses such standard strings.
Instant instant = Instant.parse( "2014-01-10T02:01:42.657Z" );
Dump to console…
System.out.println( "instant: " + instant );
When run…
instant: 2014-01-10T02:01:42.657Z
I am using following code to get date in "dd/MM/yyyy HH:mm:ss.SS" format.
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class DateAndTime{
public static void main(String[] args)throws Exception{
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss.SS");
String strDate = sdf.format(cal.getTime());
System.out.println("Current date in String Format: "+strDate);
SimpleDateFormat sdf1 = new SimpleDateFormat();
sdf1.applyPattern("dd/MM/yyyy HH:mm:ss.SS");
Date date = sdf1.parse(strDate);
System.out.println("Current date in Date Format: "+date);
}
}
and am getting following output
Current date in String Format: 05/01/2012 21:10:17.287
Current date in Date Format: Thu Jan 05 21:10:17 IST 2012
Kindly suggest what i should do to display the date in same string format(dd/MM/yyyy HH:mm:ss.SS) i.e i want following output:
Current date in String Format: 05/01/2012 21:10:17.287
Current date in Date Format: 05/01/2012 21:10:17.287
Kindly suggest
SimpleDateFormat
sdf=new SimpleDateFormat("dd/MM/YYYY hh:mm:ss");
String dateString=sdf.format(date);
It will give the output 28/09/2013 09:57:19 as you expected.
For complete program click here
You can't - because you're calling Date.toString() which will always include the system time zone if that's in the default date format for the default locale. The Date value itself has no concept of a format. If you want to format it in a particular way, use SimpleDateFormat.format()... using Date.toString() is almost always a bad idea.
The following code gives expected output. Is that what you want?
import java.util.Calendar;
import java.util.Date;
public class DateAndTime {
public static void main(String[] args) throws Exception {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss.SS");
String strDate = sdf.format(cal.getTime());
System.out.println("Current date in String Format: " + strDate);
SimpleDateFormat sdf1 = new SimpleDateFormat();
sdf1.applyPattern("dd/MM/yyyy HH:mm:ss.SS");
Date date = sdf1.parse(strDate);
String string = sdf1.format(date);
System.out.println("Current date in Date Format: " + string);
}
}
Use:
System.out.println("Current date in Date Format: " + sdf.format(date));
tl;dr
Use modern java.time classes.
Never use Date/Calendar/SimpleDateFormat classes.
Example:
ZonedDateTime // Represent a moment as seen in the wall-clock time used by the people of a particular region (a time zone).
.now( // Capture the current moment.
ZoneId.of( "Africa/Tunis" ) // Always specify time zone using proper `Continent/Region` format. Never use 3-4 letter pseudo-zones such as EST, PDT, IST, etc.
)
.truncatedTo( // Lop off finer part of this value.
ChronoUnit.MILLIS // Specify level of truncation via `ChronoUnit` enum object.
) // Returns another separate `ZonedDateTime` object, per immutable objects pattern, rather than alter (“mutate”) the original.
.format( // Generate a `String` object with text representing the value of our `ZonedDateTime` object.
DateTimeFormatter.ISO_LOCAL_DATE_TIME // This standard ISO 8601 format is close to your desired output.
) // Returns a `String`.
.replace( "T" , " " ) // Replace `T` in middle with a SPACE.
java.time
The modern approach uses java.time classes that years ago supplanted the terrible old date-time classes such as Calendar & SimpleDateFormat.
want current date and time
Capture the current moment in UTC using Instant.
Instant instant = Instant.now() ;
To view that 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.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "Pacific/Auckland" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;
Or, as a shortcut, pass a ZoneId to the ZonedDateTime.now method.
ZonedDateTime zdt = ZonedDateTime.now( ZoneId.of( "Pacific/Auckland" ) ) ;
The java.time classes use a resolution of nanoseconds. That means up to nine digits of a decimal fraction of a second. If you want only three, milliseconds, truncate. Pass your desired limit as a ChronoUnit enum object.
ZonedDateTime
.now(
ZoneId.of( "Pacific/Auckland" )
)
.truncatedTo(
ChronoUnit.MILLIS
)
in “dd/MM/yyyy HH:mm:ss.SS” format
I recommend always including the offset-from-UTC or time zone when generating a string, to avoid ambiguity and misunderstanding.
But if you insist, you can specify a specific format when generating a string to represent your date-time value. A built-in pre-defined formatter nearly meets your desired format, but for a T where you want a SPACE.
String output =
zdt.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME )
.replace( "T" , " " )
;
sdf1.applyPattern("dd/MM/yyyy HH:mm:ss.SS");
Date date = sdf1.parse(strDate);
Never exchange date-time values using text intended for presentation to humans.
Instead, use the standard formats defined for this very purpose, found in ISO 8601.
The java.time use these ISO 8601 formats by default when parsing/generating strings.
Always include an indicator of the offset-from-UTC or time zone when exchanging a specific moment. So your desired format discussed above is to be avoided for data-exchange. Furthermore, generally best to exchange a moment as UTC. This means an Instant in java.time. You can exchange a Instant from a ZonedDateTime, effectively adjusting from a time zone to UTC for the same moment, same point on the timeline, but a different wall-clock time.
Instant instant = zdt.toInstant() ;
String exchangeThisString = instant.toString() ;
2018-01-23T01:23:45.123456789Z
This ISO 8601 format uses a Z on the end to represent UTC, pronounced “Zulu”.
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.
Here's a simple snippet working in Java 8 and using the "new" date and time API LocalDateTime:
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss.SS");
LocalDateTime now = LocalDateTime.now();
System.out.println(dtf.format(now));
The output in your first printline is using your formatter. The output in your second (the date created from your parsed string) is output using Date#toString which formats according to its own rules. That is, you're not using a formatter.
The rules are as per what you're seeing and described here:
http://docs.oracle.com/javase/6/docs/api/java/util/Date.html#toString()
Disclaimer: this answer does not endorse the use of the Date class (in fact it’s long outdated and poorly designed, so I’d rather discourage it completely). I try to answer a regularly recurring question about date and time objects with a format. For this purpose I am using the Date class as example. Other classes are treated at the end.
You don’t want to
You don’t want a Date with a specific format. Good practice in all but the simplest throw-away programs is to keep your user interface apart from your model and your business logic. The value of the Date object belongs in your model, so keep your Date there and never let the user see it directly. When you adhere to this, it will never matter which format the Date has got. Whenever the user should see the date, format it into a String and show the string to the user. Similarly if you need a specific format for persistence or exchange with another system, format the Date into a string for that purpose. If the user needs to enter a date and/or time, either accept a string or use a date picker or time picker.
Special case: storing into an SQL database. It may appear that your database requires a specific format. Not so. Use yourPreparedStatement.setObject(yourParamIndex, yourDateOrTimeObject) where yourDateOrTimeObject is a LocalDate, Instant, LocalDateTime or an instance of an appropriate date-time class from java.time. And again don’t worry about the format of that object. Search for more details.
You cannot
A Date hasn’t got, as in cannot have a format. It’s a point in time, nothing more, nothing less. A container of a value. In your code sdf1.parse converts your string into a Date object, that is, into a point in time. It doesn’t keep the string nor the format that was in the string.
To finish the story, let’s look at the next line from your code too:
System.out.println("Current date in Date Format: "+date);
In order to perform the string concatenation required by the + sign Java needs to convert your Date into a String first. It does this by calling the toString method of your Date object. Date.toString always produces a string like Thu Jan 05 21:10:17 IST 2012. There is no way you could change that (except in a subclass of Date, but you don’t want that). Then the generated string is concatenated with the string literal to produce the string printed by System.out.println.
In short “format” applies only to the string representations of dates, not to the dates themselves.
Isn’t it strange that a Date hasn’t got a format?
I think what I’ve written is quite as we should expect. It’s similar to other types. Think of an int. The same int may be formatted into strings like 53,551, 53.551 (with a dot as thousands separator), 00053551, +53 551 or even 0x0000_D12F. All of this formatting produces strings, while the int just stays the same and doesn’t change its format. With a Date object it’s exactly the same: you can format it into many different strings, but the Date itself always stays the same.
Can I then have a LocalDate, a ZonedDateTime, a Calendar, a GregorianCalendar, an XMLGregorianCalendar, a java.sql.Date, Time or Timestamp in the format of my choice?
No, you cannot, and for the same reasons as above. None of the mentioned classes, in fact no date or time class I have ever met, can have a format. You can have your desired format only in a String outside your date-time object.
Links
Model–view–controller on Wikipedia
All about java.util.Date on Jon Skeet’s coding blog
Answers by Basil Bourque and Pitto explaining what to do instead (also using classes that are more modern and far more programmer friendly than Date)
If you are using JAVA8 API then this code will help.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String dateTimeString = LocalDateTime.now().format(formatter);
System.out.println(dateTimeString);
It will print the date in the given format.
But if you again create a object of LocalDateTime it will print the 'T' in between the date and time.
LocalDateTime dateTime = LocalDateTime.parse(dateTimeString, formatter);
System.out.println(dateTime.toString());
So as mentioned in earlier posts as well, the representation and usage is different.
Its better to use "yyyy-MM-dd'T'HH:mm:ss" pattern and convert the string/date object accordingly.
use
Date date = new Date();
String strDate = sdf.format(date);
intead Of
Calendar cal = Calendar.getInstance();
String strDate = sdf.format(cal.getTime());
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class DateAndTime{
public static void main(String[] args)throws Exception{
Date date = new Date(System.currentTimeMillis());
DateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss.SS",
Locale.ENGLISH);
String strDate = format.format(date);
System.out.println("Current date in String Format: "+strDate);
}
}
use this code u will get current date in expected string format
in Java, how to parse a date string that contains a letter that does not represent a pattern?
"2007-11-02T14:46:03+01:00"
String date ="2007-11-02T14:46:03+01:00";
String format = "yyyy-MM-ddTHH:mm:ssz";
new SimpleDateFormat(format).parse(date);
Exception in thread "main" java.lang.IllegalArgumentException: Illegal pattern character 'T'
at java.text.SimpleDateFormat.compile(SimpleDateFormat.java:769)
at java.text.SimpleDateFormat.initialize(SimpleDateFormat.java:576)
at java.text.SimpleDateFormat.(SimpleDateFormat.java:501)
at java.text.SimpleDateFormat.(SimpleDateFormat.java:476)
You can try
String format = "yyyy-MM-dd'T'HH:mm:ssz";
Reference : from Javadoc
Text can be quoted using single quotes
(') to avoid interpretation.
The time you're trying to parse appears to be in ISO 8601 format. SimpleDateFormat unfortunately doesn't support all the same timezone specifiers as ISO 8601. If you want to be able to properly handle all the forms specified in the ISO, the best thing to do is use Joda time.
This example is straight out of the user guide:
DateTime dt = new DateTime("2004-12-13T21:39:45.618-08:00");
No formatter needed
It’s time to post the modern answer, the answer that uses java.time, the modern Java date and time API. Your format is ISO 8601, and the classes of java.time generally parse the most common ISO 8601 variants as their default, that is, without any explicit formatter.
String date ="2007-11-02T14:46:03+01:00";
OffsetDateTime dateTime = OffsetDateTime.parse(date);
System.out.println(dateTime);
Output is:
2007-11-02T14:46:03+01:00
Yes, java.time also gives ISO 8601 format back from the toString methods, implicitly called when we print an object.
Enclose literal letters in single quotes
To answer the question as asked, you may enclose letters in single quotes to make DateTimeFormatter take them as literal letters rather than format specifiers. There would be no point whatsoever in doing the following in real code, but for the sake of demonstration:
DateTimeFormatter isoFormatter
= DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ssXXX");
String date ="2007-11-02T14:46:03+01:00";
OffsetDateTime dateTime = OffsetDateTime.parse(date, isoFormatter);
The result is the same as before.
Link
Oracle tutorial: Date Time explaining how to use java.time.
String testDate = "2007-11-02T14:46:03+01:00";
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssz");
Date date = formatter.parse(testDate);
System.out.println(date);
You can try similar to the above
You can use following link for reference
If you don't care about the time zone, you can use this method.
public static Date convertToDate(String strDate) throws ParseException {
Date date = null;
if (strDate != null) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
date = sdf.parse(strDate);
}
return date;
}
I don't know if it's still useful for you, but I encounter with the same problem now, and after a little I come up with this.
Below format code works for me !
But the code converts the date : 20220722 to date : 22-July-2022
where tradeDate = 20220722