DateTime Manipulation in C # vs Java

I am new to Java. I have the time that I get from the web page, this is in the format "hh: mm" (not 24 hours). It comes to me like a rope. Then I want to combine this string with the current date to create a Java Datethat I can use.

In C #:

string s = "5:45 PM";
DateTime d;
DateTime.TryParse(s, out d);

in Java I tried:

String s = "5:45 PM";
Date d = new Date(); // Which instantiates with the current date/time.

String[] arr = s.split(" ");
boolean isPm = arr[1].compareToIgnoreCase("PM") == 0;

arr = arr[0].split(":");
int hours = Integer.parseInt(arr[0]);
d.setHours(isPm ? hours + 12 : hours);
d.setMinutes(Integer.parseInt(arr[1]));
d.setSeconds(0);

Is there a better way to achieve what I want?

+4
source share
2 answers

Is there a better way to achieve what I want?

Absolutely - both in .NET and in Java. In .NET, I would (in a biased sense) recommend using Noda Time so that you can only imagine the time of day as LocalTimeplaying the exact pattern you expect.

Java 8 java.time.LocalTime:

import java.time.*;
import java.time.format.*;

public class Test {
    public static void main(String[] args) {
        String text = "5:45 PM";
        DateTimeFormatter format = DateTimeFormatter.ofPattern("h:mm a");
        LocalTime time = LocalTime.parse(text, format);
        System.out.println(time);
    }
}

, , , . , ZonedDateTime , , :

ZonedDateTime zoned = ZonedDateTime.now().with(time);

, - Clock .

( Noda Time, -. , .)

java.util.Date, API.

:

  • , , :
  • , ( ).

, , . ( .NET , IMO.)

+13

, , @Jon Skeet answer:

String input = "5:45 PM";
DateTimeFormatter parser = DateTimeFormatter.ofPattern("h:mm a", Locale.ENGLISH);
LocalTime time = LocalTime.parse(input, parser);

, java.util.Locale, , - AM/PM. ( , ).

, java.time.LocalDate ( ) LocalTime, LocalDateTime:

// combine with today date
LocalDateTime combined = LocalDate.now().atTime(time);

LocalDateTime :

DateTimeFormatter fmt = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm");
System.out.println(combined.format(fmt));

:

16/08/2017 17:45


LocalDateTime java.util.Date, .

A java.util.Date 1970-01-01T00:00Z ( Unix Epoch). ( ). .

, Date , , : , , , ( 1970-01-01T00:00Z), .

A LocalDateTime "local": (, ) (, , ), - .

LocalDateTime . , Date, , .

- :

// convert to system default timezone
ZonedDateTime atDefaultTimezone = combined.atZone(ZoneId.systemDefault());
// convert to java.util.Date
Date date = Date.from(atDefaultTimezone.toInstant());

/, . , :

// convert to a specific timezone
ZonedDateTime zdt = combined.atZone(ZoneId.of("Europe/London"));
// convert to java.util.Date
Date date = Date.from(zdt.toInstant());

, Europe/London. API IANA ( Region/City, America/Sao_Paulo Europe/Berlin). (, CST PST), .

( , ), ZoneId.getAvailableZoneIds().

( LocalDateTime - ). Jon ZonedDateTime ).

+2

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


All Articles