Regarding date format in java [duplicate] - java

This question already has answers here:
Java SimpleDateFormat Timezone offset with minute separated by colon
(2 answers)
Closed 2 years ago.
public class DatePgm {
public static void main(String[] args) throws ParseException {
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'+'SS:SZ");
Date date1 = sdf.parse("2020-07-26T18:52:24+05:30");
System.out.println("DATE="+sdf.format(date1));
}
}
Can any one help me to print the exact date and time format "2020-07-26T18:52:24+05:30"

tl;dr ⇒ java.time.OffsetDateTime
In this case, you don't really need to define a format/formatter yourself. The default DateTimeFormatter of an OffsetDateTime (which appears suitable here) is able to parse (and print/format) your example String. You can do it as follows:
public static void main(String[] args) {
// your example datetime String
String datetime = "2020-07-26T18:52:24+05:30";
// parse the String to an OffsetDateTime using the default formatter
OffsetDateTime odt = OffsetDateTime.parse(datetime);
// and print the OffsetDateTime using its default formatter
System.out.println("DATE=" + odt);
}
the output is
DATE=2020-07-26T18:52:24+05:30

Use Instant instead of Date. Instant supports date time with zone
Instant date1 = Instant.parse("2020-07-26T18:52:24+05:30");
System.out.println("DATE= " + date1);

You can try following,
String string = "2020-07-26T18:52:24+05:30";
OffsetDateTime odt = OffsetDateTime.parse( string );
System.out.println(odt);

You can use Calendar to get the date:
String time = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'+'SS:SZ").format(Calendar.getInstance().getTime());

I think you should use LocalDatetIme, from java 8. A very good example for most of the formats are available here

With SimpleDateFormat you have to set the timzone(Asia/Colombo is +05:30):
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
Date date1 = sdf.parse("2020-07-26T18:52:24+05:30");
sdf.setTimeZone(TimeZone.getTimeZone("Asia/Colombo"));
System.out.println("DATE="+sdf.format(date1));
Output:
DATE=2020-07-26T18:52:24+05:30

Related

How to convert 2022-08-16T06:25:00.000 to HH:mm

I'm trying to convert date from API "2022-08-16T06:25:00.000" to HH:mm (6:25) but getting DateTimeParseException.
My code: ZonedDateTime.parse(it.time[0], DateTimeFormatter.ofPattern("HH:mm"))
"time": [
"2022-08-16T06:25:00.000",
"2022-08-16T07:40:00.000"
],
String dateTimeStr = "2022-08-16T06:25:00.000";
LocalDateTime dateTime = LocalDateTime.parse(dateTimeStr);
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("HH:mm");
String time = dateTime.format(fmt);
System.out.println(time);
or, if you want to use the time as an instance of LocalTime, you can get it by dateTime.toLocalTime()
You don't need to define any DateTimeFormatter in this situation.
use a LocalDateTime because the input String does not hold any information about the zone
don't use a DateTimeFormatter for parsing that only parses hour of day and minutes of hour, the String to be parsed just contains more information
Here's an example without any DateTimeFormatter explicitly defined (but it will use default ones for parsing, at least):
public static void main(String[] args) {
// example input
String fromApi = "2022-08-16T06:25:00.000";
// parse it to a LocalDateTime because there's no zone in the String
LocalDateTime localDateTime = LocalDateTime.parse(fromApi);
// extract the time-of-day part
LocalTime localTime = localDateTime.toLocalTime();
// and print its toString() implicitly
System.out.println(localTime);
}
Output: 06:25
The above code will produce output of the pattern HH:mm, which will have leading zeros at hours of day to always have a two-digit representation.
If you insist on single-digit hours of day, you will have to prepare a DateTimeFormatter, like in this alternative example:
public static void main(String[] args) {
// example input
String fromApi = "2022-08-16T06:25:00.000";
// parse it to a LocalDateTime because there's no zone in the String
LocalDateTime localDateTime = LocalDateTime.parse(fromApi);
// extract the time-of-day part
LocalTime localTime = localDateTime.toLocalTime();
// prepare a DateTimeFormatter that formats single-digit hours of day
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("H:mm");
// print the LocalTime formatted by that DateTimeFormatter
System.out.println(localTime.format(dtf));
}
Output this time: 6:25
The other answers use Java. Since you've added a [kotlin] tag, here is a Kotlin-based answer for the sake of completeness. In order to make it different to the Java answers, I'm using kotlinx.datetime, which is still at the experimental stage at version 0.4.0.
import kotlinx.datetime.LocalDateTime
fun main() {
println(LocalDateTime.parse("2022-08-16T06:25:00.000").time) // prints "06:25"
// If you want "6:25" you can format it yourself:
println(with(LocalDateTime.parse("2022-08-16T06:25:00.000")) {
"$hour:$minute"
})
}
How about different approach
String dateTimeStr = "2022-08-16T06:25:00.000";
Matcher m=Pattern.of("T(\\d{2}:\\d{2}):").matcher(dateTimeStr);
m.find();
System.out.println(m.group(1);; //should print 06:25
And yet another "alternative" answer. It relies on the fact that in an ISO-compliant date-time format, the time starts in the 11th position.
private static final int ISO_TIME_POS = 11;
....
String dateTimeStr = "2022-08-16T06:25:00.000";
String timeStr = dateTimeStr.substring(ISO_TIME_POS, ISO_TIME_POS + 5);
System.out.println(timeStr); // prints "06:25"

Convert String date with seperator "T" to Java.sql timestamp in Java

I am trying to convert java String date into java.sql.Timestamp. I am able to convert this by using SimpleDateFormat with String date value as "2021-01-07 02:02:16.172", but when trying with the value as "2021-08-04T00:00:00.000" with seperator 'T', it gives me error. Below is the java code:
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateTest {
public static void main(String[] args) throws ParseException {
//String date = "2021-08-04T00:00:00.000Z";// How to convert this?
String date = "2021-01-07 02:02:16.172";// conversion successful
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS");
Date parsedDate = dateFormat.parse(date);
Timestamp timestamp = new java.sql.Timestamp(parsedDate.getTime());
System.out.println(timestamp);
}
}
You could use the modern API for dates, times and related information (like offsets from UTC): java.time
Strings in different formats need to be handled differently:
your first example String is formatted in ISO standard, so it can be parsed without defining a custom format. The parsing implicitly uses a DateTimeFormatter.ISO_OFFSET_DATE_TIME, which will result in an OffsetDateTime
your seconds String lacks the 'T' between date and time as well as an offset, that means you can just directly parse it to a LocalDateTime
java.sql.Timestamp got methods for conversion to java.time classes, at least to/from an Instant and a LocalDateTime. Since an Instant is a well defined moment in time, you can derive it from an OffsetDateTime:
public static void main(String[] args) throws Exception {
// your two example datetimes
String isoDateTime = "2021-08-04T00:00:00.000Z";
String customDateTime = "2021-01-07 02:02:16.172";
// you will need a custom formatter for the second one
DateTimeFormatter customDtf = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss.SSS");
// parse the Strings to java.time objects
// ISO standard, no extra formatter needed for the first one
OffsetDateTime odt = OffsetDateTime.parse(isoDateTime);
// the second one requires the formatter defined above
LocalDateTime ldt = LocalDateTime.parse(customDateTime, customDtf);
// convert them into Timestamps
Timestamp tsOne = Timestamp.from(odt.toInstant());
Timestamp tsTwo = Timestamp.valueOf(ldt);
// and print them
System.out.println("First Timestamp: " + tsOne);
System.out.println("Second Timestamp: " + tsTwo);
}
The output of this is
First Timestamp: 2021-08-04 02:00:00.0
Second Timestamp: 2021-01-07 02:02:16.172
This would be the new style...
new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSS");
would be the old style

How to convert 2017-08-01T16:00:00-04:00 to timestamp in Java?

I am looking to convert the date from default Date format to timestamp in Java.
I tried the following code, but it doesn't work:
String string = "2017-08-01T16:00:00-04:00";
DateTimeFormatter formatter =
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss-mm:ss");
LocalDate date = LocalDate.parse(string, formatter);
System.out.println(date);
java.time.format.DateTimeParseException: Text
'2017-08-01T16:00:00-04:00' could not be parsed at index 20
at
java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)
at
java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
at java.time.LocalDate.parse(LocalDate.java:400)
Don't use a LocalDate for a String that
contains information about the time of day, wich would have required a LocalDateTime and
contains an offset, wich cannot be considered by a LocalDateTime.
Instead, use an OffsetDateTime:
public static void main(String[] args) {
String string = "2017-08-01T16:00:00-04:00";
OffsetDateTime odt = OffsetDateTime.parse(string);
System.out.println(odt.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME));
}
Output:
2017-08-01T16:00:00-04:00
In addition, your pattern in DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss-mm:ss"); has serious flaws, like duplicate items.
You can of course print the result using a pattern different from the input (which complies with the ISO 8601 standard):
public static void main(String[] args) {
String string = "2017-08-01T16:00:00-04:00";
OffsetDateTime odt = OffsetDateTime.parse(string);
System.out.println(odt.format(DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm:ss Z")));
}
Output this time:
01.08.2017 16:00:00 -0400

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

How to convert current date and time in 2016-02-14T15:50:39Z format? [duplicate]

This question already has answers here:
Java string to date conversion
(17 answers)
Closed 7 years ago.
I want to convert system date and time in 2016-02-14T15:50:39Z format. How to achieve using java?
tl;dr
Instant.now()
.toString()
2018-01-23T01:23:45.678901Z
Details
The other answers use old outmoded classes.
ISO 8601
Your desired format complies with the ISO 8601 standard.
The Z on the end stands for Zulu which means UTC.
java.time
In Java 8 and later, use the built-in java.time framework.
The java.time classes use ISO 8601 formats by default when parsing/generating textual representations of date-time values.
Instant
An Instant is a moment on the time line in UTC. Its now method gets the current moment. As of Java 8 Update 74 that now method gets the current moment with millisecond resolution but future versions may get up to the full nanosecond resolution which can fit in an Instant.
The Instant::toString method generates a String just as you desire, using groups of digits (0, 3, 6, or 9) as needed for the fractional second.
String output = Instant.now().toString(); // Example: 2016-02-14T15:50:39.123Z
Truncate fractional second
If do not care about the fraction of a second, as seen in your Question’s example, truncate with a call to with, passing the ChronoField.NANO_OF_SECOND enum.
String output = Instant.now().with( ChronoField.NANO_OF_SECOND , 0 ).toString(); // Example: 2016-02-14T15:50:39Z (no '.123' at end)
Even simpler, call truncatedTo method, passing a ChronoUnit.SECONDS enum.
String output = Instant.now().truncatedTo( ChronoUnit.SECONDS ).toString();
If you want to truncate to whole minute rather than whole second, see this other Question.
Try this code:
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
public static void main(String[] args)
{
Date dt=new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
String formattedDate = formatter.format(dt);
System.out.println(formattedDate);
}
}
You can try several others date formats here.
use simple date format below is example :
Date curDate = new Date();
SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
String DateToStr = format.format(curDate);
System.out.println(DateToStr);
format = new SimpleDateFormat("dd-M-yyyy hh:mm:ss");
DateToStr = format.format(curDate);
System.out.println(DateToStr);
format = new SimpleDateFormat("dd MMMM yyyy zzzz", Locale.ENGLISH);
DateToStr = format.format(curDate);
System.out.println(DateToStr);
format = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z");
DateToStr = format.format(curDate);
System.out.println(DateToStr);
try {
Date strToDate = format.parse(DateToStr);
System.out.println(strToDate);
} catch (ParseException e) {
e.printStackTrace();
}
}

Categories

Resources