java SimpleDateFormat - java

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

Related

Format a String to a Fixed Date at UTC+0 in Java

I want to convert a String date - 2017-01-01 to java.util.Date with UTC+0. So, what I am expecting is.
"2017-01-01" -> 2017-01-01T00:00:00 UTC+0100
Here is how I am trying to do, but as my default Timezone is UTC+1, I am getting that 1 hour added to the Date.
Date d = Date.from(Instant.parse("2017-01-01T00:00:00Z"));
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss 'UTC'ZZZZZ");
String output = sf.format(d);
System.out.println(output);
Here is the output:
2017-01-01T01:00:00 UTC+0100
Can somebody help?
Your code is mixing oldfashioned and modern classes. Date and SimpleDateFormat are long outdated. Instant is modern (from 2014). I recommend you stick to the modern ones unless you are working with an old API that requires and/or gives you an instance of an oldfashioned class. So the answer is
String output = LocalDate.parse("2017-01-01")
.atStartOfDay(ZoneOffset.ofHours(1))
.format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss 'UTC'XX"));
The result is the one you asked for
2017-01-01T00:00:00 UTC+0100
The code is not really shorter than yours, but once you get used to the fluent style you will find it clearer and more natural. The room for confusion and errors is considerably reduced.
If you want the start of day in whatever time zone the user is in, just fill in ZoneId.systemDefault() instead of ZoneOffset.ofHours(1).
LocalDate parses your date string — "2017-01-01" — without an explicit format. The string conforms to ISO 8601, and the modern classes use this standard as their default for parsing and also for their toString().
You can set the timezone first and then format it.
sf.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = sf.parse(d);
And now format as per your requirements:
String output = sf.format(date);
System.out.println(output);
I wonder please try this also:
Date date = new Date();
TimeZone.setDefault(TimeZone.getTimeZone("GMT"));
Calendar cal = Calendar.getInstance(TimeZone.getDefault());
date = cal.getTime();

How do I convert an ISO 8601 date time String to java.time.LocalDateTime?

I am reading data from Wikidata. They represent their point in time property, P585 using ISO 8601 spec. However, the same beings with a +.
If I were using Joda then converting the String to joda dateTime would have been very simple.
new DateTime(dateTime, DateTimeZone.UTC);
However, when I do LocalDateTime.parse("+2017-02-26T00:00:00Z") I get an error saying can't parse the character at index 0. Is there a reason for this in Java 8. Joda does it pretty easily without any errors.
I also tried LocalDateTime.parse("+2017-02-26T00:00:00Z", DateTimeFormatter.ISO_DATE_TIME) but in vain.
How do we get around the Plus sign without having to remove it by string manipulation?
Java's DateTimeFormatter class may be of help. Here is some sample code that I believe addressses your problem (or at least gives you something to think about):
class DateTimeTester {
---
public static void main(String[] args) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("+yyyy-MM-dd'T'HH:mm:ss'Z'")
.withZone(ZoneId.of("UTC"));
LocalDateTime date = LocalDateTime.parse("+2017-02-26T01:02:03Z", formatter);
System.out.println(date);
}
}
Refer to the section called Patterns for Formatting and Parsing in the javadoc for DateTimeFormatter for details about the format-string passed to DateTimeFormatter.ofPattern().
Something to note:
Wikidata's list of available data types says about the time data type:
"explicit value for point in time, represented as a timestamp resembling ISO 8601, e.g. +2013-01-01T00:00:00Z. The year is always signed and padded to have between 4 and 16 digits.".
So Wikidata's time data type only resembles ISO 8601.
If your code needs to handle negative years (before year 0), you will need to adjust my suggested solution accordingly.
Unfortunately, the accepted answer is wrong for three reasons:
The given date-time string +2017-02-26T00:00:00Z does not represent a LocalDateTime. It represents an OffsetDateTime.
It uses a + sign with the pattern which means the pattern will fail to parse a date-time with a negative year.
'Z' is not the same as Z.
You can create the required DateTimeFormatter using the DateTimeFormatterBuilder as shown below:
class Main {
public static void main(String[] args) {
DateTimeFormatter parser = new DateTimeFormatterBuilder()
.appendValue(ChronoField.YEAR, 4, 4, SignStyle.ALWAYS)
.appendPattern("-MM-dd'T'HH:mm:ssXXX")
.toFormatter(Locale.ENGLISH);
OffsetDateTime odt = OffsetDateTime.parse("+2017-02-26T00:00:00Z", parser);
System.out.println(odt);
// If you want a LocalDateTime, you can get it from `odt`
LocalDateTime ldt = odt.toLocalDateTime();
System.out.println(ldt);
}
}
Output:
2017-02-26T00:00Z
2017-02-26T00:00
ONLINE DEMO
Learn more about the modern Date-Time API from Trail: Date Time.
A quick solution can be :
LocalDateTime.parse(yourDate, DateTimeFormatter.ISO_DATE_TIME);
Don't forget to manage the DateTimeParseException in the case of a non supported date format 😉

Java Types: What is the format for representing a variable of type `Date`? `Time`?

I have a varaibles:
Date date;
Time time;
and methods:
MyDateMethod(Date date){
//do stuff
}
MyTimeMethod(Time time){
//do stuff
}
I tried using MyDateMethod() with the following call:
MyDateMethod(1995-03-7);
I get an error saying I've supplied it with type int when it expected type Time.
I also tried using MyTimeMethod() with the following call:
MyTimeMethod(03:04:55);
I get an error saying Type mismatch: Cannot convert type int to boolean.
What is the format to put in a variable of these different types? Date is obviously not xxxx-xx-xx and Time is obviously not xx:xx:xx.
There are a few options,
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
Date d = sdf.parse("1995-03-07");
System.out.println(d);
} catch (ParseException e) {
e.printStackTrace();
}
Output is
Tue Mar 07 00:00:00 EST 1995
Or, you could use
// -1 because January is 0... I didn't design it!
Calendar c = new GregorianCalendar(1995, 3 - 1, 7);
System.out.println(c.getTime());
with the same output as before.
SimpleDateFormat is what You need. It's need to be initialized by format of date.
Use it like this:
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy/MM/dd HH:mm:ss", Locale.getDefault());
and then:
Date date = (Date) dateFormat.parse("2014/04/02 22:22:22");
Take a look at DateFormat and particularly SimpleDateFormat.
Your example would be coded like this, using SimpleDateFormat:
Date date = new SimpleDateFormat("yyyy-MM-dd").parse("1995-03-07")
(I'm assuming you have months before days here, you will need to interchange the MM and dd if not).
Java does not support Date literals. You need to use a constructor or a static factory method to obtain an instance of this class.
1995-03-07 returns 1985 because you have three int literals here and the hyphens are interpreted as subtraction operators.
Take a look at the documentation for the Date class and the DateFormat class
Here's a way you could represent these values:
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = dateFormat.parse("1995-03-07");
SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
Date time = timeFormat.parse("03:46:16");
You can use the same format objects to perform the reverse of this conversion. Please mind that these Date instances represent a specific moment in time, down to millisecond level. Internally, this is represented as the number of milliseconds since January 1, 1970, 00:00:00 GMT
This API is hardly the prettiest one in Java and by looking at the docs you can see how many changes it has undergone. Just look at the number of deprecated methods.
I recommend taking a look at the Joda-Time library instead.
Alternatively, if using Java 8 is an option for you, you can try the brand new API that comes with it
The answer by Tom is correct. No date-time literals inJava.
And as he stated, the old bundled java.util.Date and .Calendar classes are notoriously troublesome. Avoid them. Use either the Joda-Time library or the new java.time package in Java 8.
Joda-Time
In Joda-Time:
If you want only a date without time and time zone, use the LocalDate class.
Similarly to use only time while ignoring time zone and date, use the LocalTime class.
But most often you'll probably want to use the DateTime class which tracks date, time, and time zone all in one object.
A Date-Time Is Not Text
A DateTime object does not contain text. No String. If you need a string representation, use a formatter object to generate one. Search StackOverflow for many examples.
Built into Joda-Time are formatters for the sensible and increasingly common ISO 8601 standard. For example, the toString implementation on the DateTime class produces a String like this…
2014-04-01T20:17:35-08:00

Convert yyyy_mm_ddThh-mm-ss to date object?

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.

Convert String to Date in java - Time zone

I have a String, 2013-10-07T23:59:51.205-07:00, want to convert this to Java date object. I am getting parsing error.
date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").parse("2013-10-07T23:59:51.205-07:00");
try
date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ")
.parse("2013-10-07T23:59:51.205-0700");
The Z is not a literal and the timezone does not have a colon
See the examples at http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html
If java7 is being used then Z can be replaced with X and the timezone can have a colon
Z shouldn't be inside quotes. I don't think Z would work for your given timezone. Before Java 7, I guess there wasn't any format to parse ISO 8601 format timezone with colon in between. You should use -0700 instead.
However, from Java 7 onwards, you have an option for parsing ISO 8601 format timezone using X instead of Z. See javadoc for SimpleDateFormat. Just use the following format:
// This would work from Java 7 onwards
date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX")
.parse("2013-10-07T23:59:51.205-07:00");
Your pattern is wrong, you should use the following:
date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX")
.parse("2013-10-07T23:59:51.205-07:00");
The 'X' indicates the Time zone in the ISO 8601 format as expressed in your String here: '.205-07:00'
For more information read the doc: SimpleDateFormat
Use this trick to parse ISO8601 datetime format. I admit have not tried this with millisecond part within a string value maybe it gives you an extra headache. This works for Java6.
import javax.xml.bind.DatatypeConverter;
Calendar cal = DatatypeConverter.parseDateTime(strDatetime);
If am remembering correct cal instance may not use a system-default timezone. Its initialized to the origin string value timezone. If you want instance to use system timezone you can do this conversion.
long ts = cal.getTimeInMillis();
cal = Calendar.getInstance();
cal.setTimeInMillis(ts);
You should use XXX for the format -07:00, instead of Z and X.
Date sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX")
.parse("2013-10-07T23:59:51.205-07:00");
Look at the example of this docs.
The problem is that -07:00 is not a valid Time zone . The Time Zone should have this format, for example something like -0800.

Categories