Parsing timestamp with "T" between date and time - java

I am trying to parse a timestamp I received from database, I have tried multiple parsing string, but every each of them did not work. I am trying to extract the date and clock.
import java.util.Locale;
import java.util.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class Main{
public static void main(String []args){
try {
// error here!
SimpleDateFormat postgre = new SimpleDateFormat("yyyy-MM-ddXHH:mm:ss.ms", Locale.getDefault());
Date d = postgre.parse("2019-08-07T09:51:17.222Z");
System.out.println(new SimpleDateFormat("HH:mm", Locale.getDefault()).format(d));
System.out.println(new SimpleDateFormat("dd MMMMM yyyy", Locale.getDefault()).format(d));
} catch (Exception e){
System.out.println(e.getMessage());
}
}
}
yes, I need to use legacy class.

tl;dr
Simple one-liner using the modern java.time classes that years ago supplanted the terrible legacy classes such as Date and SimpleDateFormat.
java.time.Instant
.parse(
"2019-08-07T09:51:17.222Z"
)
.atOffset(
ZoneOffset.UTC
)
.toLocalDate()
For time-of-day portion, call toLocalTime().
To see the same moment through the wall-clock time used by the people of a particular region (a time zone), apply ZoneId to get a ZonedDateTime object. Then call toLocalDate and LocalTime.
Details
Parse using modern class, Java.time.Instant.
Your input string is in standard ISO 8601 format. The java.time classes use these standard formats by default when parsing/generating strings. So no need to specify a formatting pattern.
Instant instant = Instant.parse( "2019-08-07T09:51:17.222Z" ) ;
Generate an ISO 8601 string.
String output = instant.toString() ;
To write to database, convert to sibling class OffsetDateTime. While support for Instant is optional in JDBC 4.2 and later, your JDBC driver is required to support OffsetDateTime.
OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC ) ;
myPreparedStatement.setObject( … , odt ) ;
Retrieval.
OffsetDateTime odt = myResultSet.getObject( … , OffsetDateTime.class ) ;
Instant instant = odt.toInstant() ;
If you want to see the date and the time-of-day for that moment as seen in UTC (as opposed to some time zone), extract a LocalDate and LocalTime.
LocalDate ld = odt.toLocalDate() ;
LocalTime lt = odt.toLocalTime() ;
Best to avoid the terrible legacy class java.util.Date. But if you must, you can convert back and forth using new to/from methods added to the old classes.
java.util.Date d = Date.from( instant ) ;
Likewise, when receiving a Date, immediately convert to an Instant. Then proceed with your business logic.
Instant instant = myDate.toInstant() ;

The correct pattern is "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'". I forgot to use the capital S for milliseconds.

Related

convert string date to sql date format

I want to convert this string "2022-01-13 14:33:07.996" to java sql date. I have read the answers and I have converted the string to java util date and then to java sql date. I just don't know how to get the full date in java sql date format
String dateStart = "2022-01-13 14:33:07.996";
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date date1 = dateFormat.parse(dateStart);
java.util.Date utilDate = date1;
java.sql.Date sqlDate = new java.sql.Date(date1.getTime());
System.out.println(sqlDate);
in out put i get this
2022-01-13
but I want something like this 2022-01-13 14:33:07.996 in java sql date format
tl;dr
To write date-time values to a database, use appropriate objects, not text. For a date-only value, use LocalDate.
myPreparedStatement
.setObject(
… ,
LocalDateTime
.parse( "2022-01-13 14:33:07.996".replace( " " , "T" ) )
.toLocalDate()
)
Avoid legacy date-time classes
You are using terrible date-time classes that were years ago supplanted by the modern java.time classes defined in JSR 310.
Date-only
You said:
2022-01-13 14:33:07.996 in java sql date format
That is a contradiction. A java.sql.Date object represents a date-only, not a date with time-of-day.
java.time.LocalDateTime
Parse your input string as a LocalDateTime because it lacks any indicator of time zone or offset. Replace the SPACE in the middle with a T to comply with the ISO 8601 standard.
String input = "2022-01-13 14:33:07.996".replace( " " , "T" ) ;
LocalDateTime ldt = LocalDateTime.parse( input ) ;
java.time.LocalDate
Extract the date portion.
LocalDate ld = ldt.toLocalDate() ;
Database access
Write to database.
myPreparedStatement.setObject( … , ld ) ;
Retrieve from database.
LocalDate ld = myResultSet.getObject( … , LocalDate.class ) ;
These matters have been covered many many times already on Stack Overflow. Search to learn more.

Java - Date format for Multiple Scenarios

I have a java component to format the date that I retrieve. Here is my code:
Format formatter = new SimpleDateFormat("yyyyMMdd");
String s = "2019-04-23 06:57:00.0";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss.S");
try
{
Date date = simpleDateFormat.parse(s);
System.out.println("Formatter: "+formatter.format(date));
}
catch (ParseException ex)
{
System.out.println("Exception "+ex);
}
The code works great as long as the String s has the format "2019-04-23 06:57:00.0";
My Question is, how to tweak this code so it will work for below scenarios ex,
my s string may have values like
String s = "2019-04-23 06:57:00.0";
or
String s = "2019-04-23 06:57:00";
Or
String s = "2019-04-23";
right now it fails if I don't pass the ms.. Thanks!
Different types
String s = "2019-04-23 06:57:00";
String s = "2019-04-23";
These are two different kinds of information. One is a date with time-of-day, the other is simply a date. So you should be parsing each as different types of objects.
LocalDateTime.parse
To comply with the ISO 8601 standard format used by default in the LocalDateTime class, replace the SPACE in the middle with a T. I suggest you educate the publisher of your data about using only ISO 8601 formats when exchanging date-time values as text.
LocalDateTime ldt1 = LocalDateTime.parse( "2019-04-23 06:57:00".replace( " " , "T" ) ) ;
The fractional second parses by default as well.
LocalDateTime ldt2 = LocalDateTime.parse( "2019-04-23 06:57:00.0".replace( " " , "T" ) ) ;
See this code run live at IdeOne.com.
ldt1.toString(): 2019-04-23T06:57
ldt2.toString(): 2019-04-23T06:57
LocalDate.parse
Your date-only input already complies with ISO 8601.
LocalDate ld = LocalDate.parse( "2019-04-23" ) ;
See this code run live at IdeOne.com.
ld.toString(): 2019-04-23
Date with time-of-day
You can strip out the time-of-day from the date.
LocalDate ld = ldt.toLocalDate() ;
And you can add it back in.
LocalTime lt = LocalTime.parse( "06:57:00" ) ;
LocalDateTime ldt = ld.with( lt ) ;
Moment
However, be aware that a LocalDateTime does not represent a moment, is not a point on the timeline. Lacking the context of a time zone or offset-from-UTC, a LocalDateTime cannot hold a moment, as explained in its class JavaDoc.
For a moment, use the ZonedDateTime, OffsetDateTime, or Instant classes. Teach the publisher of your data to include the offset, preferably in UTC.
Avoid legacy date-time classes
The old classes SimpleDateFormat, Date, and Calendar are terrible, riddled with poor design choices, written by people not skilled in date-time handling. These were supplanted years ago by the modern java.time classes defined in JSR 310.
In case of you have optional parts in pattern you can use [ and ].
For example
public static Instant toInstant(final String timeStr){
final DateTimeFormatter formatter = DateTimeFormatter
.ofPattern("yyyy-MM-dd HH[:mm[:ss[ SSSSSSSS]]]")
.withZone(ZoneId.of("UTC"));
try {
return Instant.from(formatter.parse(timeStr));
}catch (DateTimeException e){
final DateTimeFormatter formatter2 = DateTimeFormatter
.ofPattern("yyyy-MM-dd")
.withZone(ZoneId.of("UTC"));
return LocalDate.parse(timeStr, formatter2).atStartOfDay().atZone(ZoneId.of("UTC")).toInstant();
}
}
cover
yyyy-MM-dd
yyyy-MM-dd HH
yyyy-MM-dd HH:mm
yyyy-MM-dd HH:mm:ss
yyyy-MM-dd HH:mm:ss SSSSSSSS

Plus 1 hour and 1 day in date using java 8 apis

I have this code to add 1 hour or 1 day in date Java 8, but doesn´t work
String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
java.text.SimpleDateFormat format = new java.text.SimpleDateFormat(DATE_FORMAT);
Date parse = format.parse("2017-01-01 13:00:00");
LocalDateTime ldt = LocalDateTime.ofInstant(parse.toInstant(), ZoneId.systemDefault());
ldt.plusHours(1);
ZonedDateTime zdt = ldt.atZone(ZoneId.systemDefault());
Date te = Date.from(zdt.toInstant());
What´s wrong? The code shows: Sun Jan 01 13:00:00 BRST 2017
LocalDateTime is immutable and returns a new LocalDateTime when you call methods on it.
So you must call
ldt = ldt.plusHours(1);
Apart from the issue that you don't use the result of your date manipulation (ldt = ldt.plusHours(1)), you don't really need to go via a LocalDateTime for this operation.
I would simply use an OffsetDateTime since you don't care about time zones:
OffsetDateTime odt = parse.toInstant().atOffset(ZoneOffset.UTC);
odt = odt.plusDays(1).plusHours(1);
Date te = Date.from(odt.toInstant());
You could even stick to using Instants:
Instant input = parse.toInstant();
Date te = Date.from(input.plus(1, DAYS).plus(1, HOURS));
(with an import static java.time.temporal.ChronoUnit.*;)
tl;dr
LocalDateTime.parse( // Parse input string that lacks any indication of offset-from-UTC or time zone.
"2017-01-01 13:00:00".replace( " " , "T" ) // Convert to ISO 8601 standard format.
).atZone( // Assign a time zone to render a meaningful ZonedDateTime object, an actual point on the timeline.
ZoneId.systemDefault() // The Question uses default time zone. Beware that default can change at any moment during runtime. Better to specify an expected/desired time zone generally.
).plus(
Duration.ofDays( 1L ).plusHours( 1L ) // Add a span of time.
)
Details
Do not mix the troublesome old legacy classes Date and Calendar with the modern java.time classes. Use only java.time, avoiding the legacy classes.
The java.time classes use the ISO 8601 standard formats by default when parsing and generating strings. Convert your input string by replacing the SPACE in the middle with a T.
String input = "2017-01-01 13:00:00".replace( " " , "T" ) ;
LocalDateTime ldt = LocalDateTime.parse( input ) ;
ALocalDateTime does not represent an actual moment, not a point on the timeline. It has no real meaning until you assign a time zone.
ZoneId z = ZoneId.systemDefault() ; // I recommend specifying the desired/expected zone rather than relying on current default.
ZonedDateTime zdt = ldt.atZone( z ) ;
A Duration represents a span of time not attached to the timeline.
Duration d = Duration.ofDays( 1L ).plusHours( 1L ) ;
ZonedDateTime zdtLater = zdt.plus( d ) ;

Dates and Timezones in java

I am currently reading dates in JSON format as follows:
"dates": {
"startdate": "2017-08-29T22:00:00.000UTC";
}
And in my application, I set the JsonFormat as follows to be able to read it correctly:
#JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'UTC'")
private Date startdate;
But UTC isn't the TimeZone I want to work with, what should I change 'UTC' into to be able to read my dateTime in the Europe/Paris zone?
Alter the input to comply with the ISO 8601 standard. The Z is short for Zulu and means UTC.
String input = "2017-08-29T22:00:00.000UTC".replace( "UTC" , "Z" ) ;
Parse as an Instant object.
Instant instant = Instant.parse( input ) ;
Adjust into your desired time zone.
ZoneId z = ZoneId.of( "Europe/Paris" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;
Avoid the Date class as that troublesome class is now legacy, supplanted by the java.time classes.

How to set offset of a java.util.Date?

I have a Date as a String - 15Sep20162040, which I have to format it into another format with Timezone as 2016-09-15T20:40:00+0400.
What I did to do it as follows:
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class DateFormatExample {
private static SimpleDateFormat offsetDateFormat = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ssZ");
private static SimpleDateFormat dateFormatter = new SimpleDateFormat(
"ddMMMyyyyHHmm");
public static void main(String[] args) throws ParseException {
String date = "15Sep20162040";
String result = offsetDateFormat.format(dateFormatter.parse(date));
System.out.println(result); // 2016-09-15T20:40:00+0400
}
}
Now, I have to modify the output based on timezone difference, for example if difference is +0100, output should resemble as: 2016-09-15T20:40:00+0100 and if difference is -0200, output should resemble as: 2016-09-15T20:40:00-0200.
How can I achieve it?
You can use SimpleDateFormat's setTimeZone method as below:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.TimeZone;
public class DateFormatExample {
private static SimpleDateFormat offsetDateFormat = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ssZ");
private static SimpleDateFormat dateFormatter = new SimpleDateFormat(
"ddMMMyyyyHHmm");
public static void main(String[] args) throws ParseException {
String date = "15Sep20162040";
String result = offsetDateFormat.format(dateFormatter.parse(date));
System.out.println(result); // 2016-09-15T20:40:00+0400
offsetDateFormat.setTimeZone(TimeZone.getTimeZone("GMT-8:00"));
result = offsetDateFormat.format(dateFormatter.parse(date));
System.out.println(result);
}
}
If you simply want to change the timezone at the end of result, please try the following:
String offset = "GMT-8:00";
String date = "15Sep20162040";
date = date+" "+offset;
SimpleDateFormat dateFormatter2 = new SimpleDateFormat("ddMMMyyyyHHmm Z");
SimpleDateFormat offsetDateFormat2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
offsetDateFormat2.setTimeZone(TimeZone.getTimeZone(offset));
String result = offsetDateFormat2.format(dateFormatter2.parse(date));
System.out.println(result);
Hope this helps.
tl;dr
ZonedDateTime zdt =
LocalDateTime.parse ( "15Sep20162040" ,
DateTimeFormatter.ofPattern ( "ddMMMyyyyHHmm" )
.withLocale( Locale.English )
)
.atZone ( ZoneId.of ( "America/Puerto_Rico" ) );
2016-09-15T20:40-04:00[America/Puerto_Rico]
zdt.atZone( ZoneId.of ( "Pacific/Auckland" ) ) // Same moment viewed through different wall-clock time
2016-09-16T12:40+12:00[Pacific/Auckland]
Using java.time
Avoid the troublesome old date-time classes, now supplanted by the java.time classes.
Define a formatting pattern to match your input string.
String input = "15Sep20162040";
DateTimeFormatter f = DateTimeFormatter.ofPattern ( "ddMMMyyyyHHmm" ).withLocale ( Locale.ENGLISH );
By the way, this is a terrible format for a date-time string. It assumes English, abuses English with incorrect abbreviation of month name, and is confusing and ambiguous. Instead, use the standard ISO 8601 formats when serializing date-time values to text.
Un-zoned
Parse the input string as a LocalDateTime since it lacks any info about offset-from-UTC or time zone.
LocalDateTime ldt = LocalDateTime.parse ( input , f );
Understand that without an offset or time zone, this LocalDateTime object has no real meaning. It represents many possible moments, but not a specific point on the timeline. For example, noon in Auckland NZ is a different moment than noon in Kolkata India which is an earlier moment than noon in Paris France.
Assign an offset-from-UTC
You indicate this date-time was intended to be a moment with an offset-from-UTC of four hours behind UTC (-04:00). So next we apply a ZoneOffset to get a OffsetDateTime object.
Tip: Always include the colon and the minutes and padding zeros in your offset-from-UTC strings. While not required by the ISO 8601 standard, common software libraries and protocols expect the fuller formatting.
ZoneOffset offset = ZoneOffset.ofHours( -4 );
OffsetDateTime odt = ldt.atOffset( offset );
Assign a time zone
If by your context you knew of a time zone rather than a mere offset, use a ZoneId to instantiate a ZonedDateTime object. A time zone is an offset plus a set of rules for handling anomalies such as Daylight Saving Time (DST).
Specify a proper time zone name in the format of continent/region. 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( "America/Puerto_Rico" );
ZonedDateTime zdt = ldt.atZone( z );
Different time zones
Your question is not clear near the end, about changing offsets. If your goal is to view the date-time through the various lenses of various time zones, you can easily adjust by creating new ZonedDateTime objects. Assign a different time zone to each.
Note that all these date-time objects (zdt, zKolkata, and zAuckland) represent the same moment, the same point on the timeline. Each presents a different wall-clock time but for the same simultaneous moment.
ZoneId zKolkata = ZoneId.of ( "Asia/Kolkata" );
ZonedDateTime zdtKolkata = zdt.withZoneSameInstant ( zKolkata );
ZoneId zAuckland = ZoneId.of ( "Pacific/Auckland" );
ZonedDateTime zdtAuckland = zdt.withZoneSameInstant ( zAuckland );
System.out.println ( "input: " + input + " | ldt: " + ldt + " | odt: " + odt + " | zdt: " + zdt + " | zdtKolkata " + zdtKolkata + " | zdtAuckland: " + zdtAuckland );
Dump to console.
input: 15Sep20162040 | ldt: 2016-09-15T20:40 | odt: 2016-09-15T20:40-04:00 | zdt: 2016-09-15T20:40-04:00[America/Puerto_Rico] | zdtKolkata 2016-09-16T06:10+05:30[Asia/Kolkata] | zdtAuckland: 2016-09-16T12:40+12:00[Pacific/Auckland]
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.

Categories

Resources