Java formatting a date [duplicate] - java

This question already has answers here:
Java SimpleDateFormat Timezone offset with minute separated by colon
(2 answers)
Closed 5 years ago.
I have a problem formatting a date. I want the following output:
yyyy-MM-ddTHH:mm:ss+02:00
Where +02:00 depends on the timezone where you are, in my case Europe/Amsterdam
I have this function:
public String marshal(Date d) throws Exception
{
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
String s = formatter.format(d);
return s;
}
But it gives me:
2017-05-10T14:56:46+0200
How can I have the timezone hour/minute with an extra colon in between?

It's right there in the documentation:
The number of pattern letters designates the format for both formatting and parsing as follows [...]
And from the examples:
"yyyy-MM-dd'T'HH:mm:ss.SSSXXX" 2001-07-04T12:08:56.235-07:00
Meaning that the colon-separated version of the timezone can be expressed using "XXX" in the pattern.
TL;DR: use
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");

Related

Java DateTimeFormatter is not parsing as expected [duplicate]

This question already has answers here:
`uuuu` versus `yyyy` in `DateTimeFormatter` formatting pattern codes in Java?
(4 answers)
Issue with DateTimeParseException when using STRICT resolver style
(2 answers)
Closed 2 years ago.
I tried DateTimeFormatter to parse input date to dd/MM/yyyy. I have used below code
java.time.format.DateTimeFormatter is failing to parse the date
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy").withResolverStyle(ResolverStyle.STRICT);
try {
LocalDate.parse(dateField, dateFormatter);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
Input: 30/04/2018
Error:Caused by: java.time.DateTimeException: Unable to obtain LocalDate from TemporalAccessor: {MonthOfYear=4, YearOfEra=2018, DayOfMonth=30},ISO of type java.time.format.Parsed
It is also failing for leap years.
The issue is using .withResolverStyle(ResolverStyle.STRICT) requires to use year pattern uuuu instead of yyyy (i.e. "year" instead of "year-of-era")
You basically have two options (here, where one is using the ResolverStyle you are showing in your code example):
use a ResolverStyle.STRICT explicitly ⇒ parses year u only
use a default ResolverStyle ⇒ year-of-era y or year u will be parsed
The following example shows the differences in code:
public static void main(String[] args) {
String date = "30/04/2018";
// first formatter with year-of-era but no resolver style
DateTimeFormatter dtfY = DateTimeFormatter.ofPattern("dd/MM/yyyy");
// second one with year and a strict resolver style
DateTimeFormatter dtfU = DateTimeFormatter.ofPattern("dd/MM/uuuu")
.withResolverStyle(ResolverStyle.STRICT);
// parse
LocalDate localDateU = LocalDate.parse(date, dtfU);
LocalDate localDateY = LocalDate.parse(date, dtfY);
// print results
System.out.println(localDateU);
System.out.println(localDateY);
}
The output is
2018-04-30
2018-04-30
so both DateTimeFormatters parse the very same String, but the one without a ResolverStyle explicitly attached will use ResolverStyle.SMART by default according to the JavaDocs of DateTimeFormatter.
Of course, a pattern with year (u) will be parsed by ResolverStyle.SMART, too, so
DateTimeFormatter.ofPattern("dd/MM/uuuu");
would be an option as well.
A good explanation of the difference between year-of-era and year can be found in this post.

How to decode the date in Android? - DATETIMESTAMP [duplicate]

This question already has answers here:
Android: Compare time in this format `yyyy-mm-dd hh:mm:ss` to the current moment
(5 answers)
Conversion of a date to epoch Java [duplicate]
(4 answers)
How to get the current time in YYYY-MM-DD HH:MI:Sec.Millisecond format in Java?
(16 answers)
Closed 2 years ago.
The following code gave me Datetimestamp as [ 2020-07-183 17:07:55.551 ]. The issue is with "Day" in Datetimestamp, which has three digits. How to format currentTimeMillis into the right format for day of month?
public String Datetimesetter(long currentTimeMillis, SimpleDateFormat dateFormat) {
dateFormat = new SimpleDateFormat("YYYY-MM-DD HH:MM:SS.SSS");
// Create a calendar object that will convert the date and time value in milliseconds to date.
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(currentTimeMillis);
return dateFormat.format(calendar.getTime());
}
SOLUTION WHICH WORKED FOR ME:
Please visit this link.
This is for the case you are supporting Apps from API level 26 (native support of java.time) or you are willing / allowed to use a backport library of the same functionality.
Then you can use a correct / matching pattern (one that considers three-digit days) like this:
public static void main(String[] args) {
// mock / receive the datetime string
String timestamp = "2020-07-183 17:07:55.551";
// create a formatter using a suitable pattern (NOTE the 3 Ds)
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-DDD HH:mm:ss.SSS");
// parse the String to a LocalDateTime using the formatter defined before
LocalDateTime ldt = LocalDateTime.parse(timestamp, dtf);
// and print its default String representation
System.out.println(ldt);
}
which outputs
2020-07-01T17:07:55.551
So I guess the day of year no. 183 was actually July 1st.
your date format is incorrect
dateFormat = new SimpleDateFormat("YYYY-MM-DD HH:MM:SS.SSS");
change to this
dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:MM:SS.SSS");

Android: Parsing datetime with timezone using DateTimeFormatter [duplicate]

This question already has answers here:
Parse String to date with timezone offset intact
(1 answer)
Java date offset format issue?
(4 answers)
DateTimeFormatter create pattern [duplicate]
(1 answer)
Closed 2 years ago.
Convert string '2018-08-27T16:40:02+08:00' to datetime using DateTimeFormatter
private static final String DATE_TIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss";
String rawDateString = "2018-08-27T16:40:02+08:00"
DateTimeFormatter dateTimeFormatter =
DateTimeFormatter.ofPattern(DATE_TIME_FORMAT, Locale.ENGLISH);
LocalDateTime localDateTime = LocalDateTime.parse(rawDateString, dateTimeFormatter);
return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
but this returns DateTimeParseException: Text could not be parsed at index 19
I saw some similar issue like this
DateTimeParseException: Text could not be parsed at index 2
but I dont see any sample with timezone on datetime format.
You neeed to specify timezone offset in your format as well. Like that:
String DATE_TIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ssXXX";
See the link bellow:
https://www.journaldev.com/17899/java-simpledateformat-java-date-format

Is there a way to using date format's offset parameter with colon? [duplicate]

This question already has answers here:
Java SimpleDateFormat Timezone offset with minute separated by colon
(2 answers)
Closed 3 years ago.
I'm using java's SimpleDateFormat, here is my code:
Date date = new Date();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSSZ");
String strDate = simpleDateFormat.format(date);
System.out.println(strDate);
Which print out:
2019-11-15T11:59:47.289+0200
But, I want to have a colon inside the offset, which means it need to look like this:
2019-11-15T11:59:47.289+02:00
Is there a way to adding a time zone that printed out like the second example here?
What you are talking about is not a time zone (like UTC), it is an offset (like +01:00).
You can use the modern date time API java.time, which has a built-in DateTimeFormatter.ISO_OFFSET_DATE_TIME, that formats the offset as desired:
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
public class StackoverflowDemo {
public static void main(String[] args) {
OffsetDateTime odt = OffsetDateTime.now();
System.out.println(odt.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME));
}
}
The output on my system is this:
2019-11-15T11:30:46.532+01:00
this snippet below gives result like this
2019-11-15T16:03:53+05:30
SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
System.out.println(dateFormat2.format(new Date()));
hope this is what you are looking for
Your format should be yyyy-MM-dd'T'hh:mm:ss.SSSXXX
I think your best bet is to use DateTimeFormatter.
You can find documentation here:
https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html

Single pattern for java 8 date time [duplicate]

This question already has answers here:
JSR-310 - parsing seconds fraction with variable length
(4 answers)
Java 8 Date equivalent to Joda's DateTimeFormatterBuilder with multiple parser formats?
(5 answers)
Closed 4 years ago.
public static long convertDateTimeToEpochMillis(String eventDate,String eventTime) {
String patternMills = "yyyy-MM-dd HH:mm:ss.SSS";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern(pattern);
LocalDateTime localDateTime = LocalDateTime.parse(eventDate + " " +
eventTime, dtf);
}
This is giving a parsing exception when I am passing 2018-07-19 23:11:52.3 but parses successfully for 2018-07-19 23:11:52.312. I don't want to specify 3 different patterns for different times like yyyy-MM-dd HH:mm:ss.S,yyyy-MM-dd HH:mm:ss.SS and yyyy-MM-dd HH:mm:ss.SSS.
Can I provide a single pattern which will take up to 1/10th of a sec, 100th of a sec and millisec?
ISO 8601
Actually your pattern is not far from accepted by LocalDateTime.parse default pattern, using standard ISO 8601 format.
So, maybe put not a space but letter T instead will be enough for you?
Then you do not need DateTimeFormatter at all.
LocalDateTime localDateTime = LocalDateTime.parse(eventDate + "T" +
eventTime);
It accepts any number of digits in milliseconds part, from 0 up to 9.
You can just choose a pattern with three SSS as default
String patternMills = "yyyy-MM-dd HH:mm:ss.SSS";
and fulfill right side of your date with zeros when necessary
String eventDate = "2018-07-19 23:11:52.3";
String millis = eventDate.substring(eventDate.lastIndexOf('.')+1);
if(millis.length() < 3)
eventDate += Stream.generate(() -> "0").limit(3 - millis.length()).collect(Collectors.joining(""));
or use nice apache method:
StringUtils.rightPad(eventDate, 23, '0'); // 23 is string length for "yyyy-MM-dd HH:mm:ss.SSS" pattern
Anyway you can also add some validation to check the rest part of the date string

Categories

Resources