How to convert String to Date using TimeZone?

I am trying to convert mine Stringto Date+ timezone. I get my string from a variable DateTime(here: xyz). My code is:

String abc = xyz.toString("yyyy-MM-ddZZ");
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-ddXXX");
java.util.Date date = sdf.parse(abc);
System.out.println("Date: " + sdf.format(date));

Error:

Invalid format: "2017-01-03 + 01: 00" is distorted at "+01: 00"

If I try SimpleDateFormat("yyyy-MM-dd");, it works, but without a time zone ("+01: 00")

-1
source share
3 answers
    String abc = "2017-01-03+01:00";
    TemporalAccessor parsed = DateTimeFormatter.ISO_OFFSET_DATE.parse(abc);
    LocalDate date = LocalDate.from(parsed);
    ZoneOffset offset = ZoneOffset.from(parsed);
    System.out.println("Date: " + date + "; offset: " + offset + '.');

Fingerprints:

Date: 2017-01-03; offset: +01:00.

java.time, API Java, . Date (, ) SimpleDateFormat, , . . API . java.util.Date / java.util.TimeZone API, , :

    Date oldfashionedDate = Date.from(date.atStartOfDay(offset).toInstant());
    TimeZone oldfashionedTimeZone = TimeZone.getTimeZone(offset);
    System.out.println("Old-fashioned date: " + oldfashionedDate
            + "; old-fashioned time-zone: " + oldfashionedTimeZone.getDisplayName() + '.');

:

Old-fashioned date: Tue Jan 03 00:00:00 CET 2017; old-fashioned time-zone: GMT+01:00.

, UTC, , . , Date.toString() JVM , Date - .

? LocalDate, Date , . , , -, "ISO-8601-like" , ​​ , ISO . Java OffsetDate ZonedDate, , . , , ThreeTen-Extra, .

+1

- , , - - UTC - java.util.Date, : , , , .

SimpleDateFormat , "", . , X Java, .

Java 8, . , , , java.util.Date, :

DateTimeFormatter fmt = new DateTimeFormatterBuilder().append(DateTimeFormatter.ISO_OFFSET_DATE)
    // set hour to midnight
    .parseDefaulting(ChronoField.HOUR_OF_DAY, 0).toFormatter();

OffsetDateTime odt = OffsetDateTime.parse("2017-01-03+01:00", fmt); // 2017-01-03T00:00+01:00

OffsetDateTime , , , , SimpleDateFormat , , .

. java.util.Date:

Date date = Date.from(odt.toInstant());

"" , :

// get just the date
LocalDate localDate = odt.toLocalDate(); // 2017-01-03
// get just the offset
ZoneOffset offset = odt.getOffset(); // +01:00

PS: +01:00 , . .

+1

"2017-01-03 + 01: 00"

, ISO 8601, ISO 8601. @Meno Hochschild @Basil Bourque.

, : javax.xml.bind.DatatypeConverter.parseDateTime, Calendar:

System.out.println(DatatypeConverter.parseDate("2017-01-03+01:00").getTime());

:

Tue Jan 03 07:00:00 CST 2017

From the javadoc method:

public static calendar parseDate (String lexicalXSDDate)
Converts a string argument to a calendar value.

Parameters: lexicalXSDDate - a string containing the lexical representation of xsd: Date.

 Returns: calendar value represented by string argument.

 Throws: IllegalArgumentException - if the string parameter does not match the lexical value space defined in XML Schema 2: Data types for xsd: Date.

0
source

Source: https://habr.com/ru/post/1693356/


All Articles