简体   繁体   中英

How to convert C# DateTime to Java DateTime

I am new to Java and I already have c# code which I have to convert it into java, but am not able to find good alternative to it.

Below is the code that I want to convert:

private string GetDate(object value)
    {
        DateTime start = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
        var lastWeek = DateTime.Today.AddDays(-6);
        var date = start.AddMilliseconds((long)value).ToLocalTime();
        if (date >= lastWeek)
        {
            if (date.DayOfWeek == DateTime.Now.DayOfWeek)
                return "Today";
            else
                return date.DayOfWeek.ToString();
        }
        else
            return date.ToString("dd-MM-yyy");
    }

I tried using Calendar class at first, but it's giving error that integer number too large:

    Calendar cal = Calendar.getInstance();
    cal.set(1970, 0, 1, 0, 0, 0);
    cal.set(Calendar.MILLISECOND, 0);
    long result = cal.getTimeInMillis();
    long value = result + 1406205185123;

Any solution/suggestion will be helpful.

I haven't checked if it satisfies all your requirements regarding the output, but I think it will give enough pointers to help you out. Depending on your needs you need a ZonedDateTime (which has a timezone), or a LocalDateTime , which is the date as people speak about it in a country.

  private String getDate(long value) {
    LocalDateTime now = LocalDateTime.now();
    LocalDateTime start = LocalDateTime.of(1970, 1, 1, 0, 0, 0, 0);
    LocalDateTime lastWeek = now.minusDays(6);
    LocalDateTime date = start.plus(value, ChronoUnit.MILLIS);

    if (lastWeek.isBefore(date)) {
        DayOfWeek dayOfWeek = date.getDayOfWeek();
        if (dayOfWeek == now.getDayOfWeek()) {
            return "Today";
        } else {
            return dayOfWeek.name();
        }
    } 


    return date.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT));
}

I've also took the liberty to convert the code style to what is usual in Java, which is the placing of the opening brace, the capitalization of functions.

More on the date/time classes can be found in the Oracle Trail on date/time .

tl;dr

ZoneId z = ZoneId.of( "Pacific/Auckland" ) ;  // The time zone of your business context.
LocalDate input = Instant.ofEpochMilli( yourMillis ).atZone( z ).toLocalDate() ;
LocalDate today = LocalDate.now( z ) ;
LocalDate weekAgo = today.minusDays( 6 ) ;
if ( input.isAfter( today ) ) { … error }
else if ( input.isEqual( today ) ) { return "Today" ; }
else if ( ! input.isBefore( weekAgo ) ) { return input.getDayOfWeek().getDisplayName( TextStyle.FULL , Locale.US ) ; }
else if ( input.isBefore( weekAgo ) ) { return input.format( DateTimeFormatter.ofPattern( "dd-MM-uuuu" ) ) ; }
else { … error, unreachable point } 

Details

DateTime start = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

Instead, for a point on the timeline in UTC, use Instant . The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).

Your example of first moment of 1970 UTC happens to be the epoch reference used by the java.time framework. And it happens to be defined as a constant .

Instant start = Instant.EPOCH ;

Add your count of milliseconds.

Instant later = start.plusMillis( yourMillis ) ;

But if your count of milliseconds is always a count since the epoch reference, then you can shorten that code above.

Instant instantInput = Instant.ofEpochMilli( yourMillis ) ; // Determine a moment in UTC from a count of milliseconds since 1970-01-01T00:00Z. 

Apparently your goal is to compare dates or day-of-week. Both of those require a time zone. You ignore this crucial issue in your Question. For any given moment, the date varies around the globe by zone. At this moment right now is Monday in the United States, but in New Zealand it is “tomorrow” Tuesday.

Apply a ZoneId to get a ZonedDateTime . Same moment, same point on the timeline, but seen through the wall-clock time used by the people of a particular region (a time zone).

ZoneId z = ZoneId.of( "Asia/Kolkata" ) ;
ZonedDateTime zdtInput = instantInput.atZone( z ) ;

Extract the date-only, without a time-of-day and without a time zone.

LocalDate ldInput = zdtInput.toLocalDate() ;

Extract the day-of-week, represented by the DayOfWeek enum.

DayOfWeek dowInput = ldInput.getDayOfWeek() ;

Subtract six days from now. Represent the six days as TemporalAmount , either six calendar days in a Period or six chunks of 24-hours as a Duration .

Period sixDays = Period.ofDays( 6 ) ;
LocalDate today = LocalDate.now( z ) ;
LocalDate sixDaysBeforeToday = today.minus( sixDays ); // Or LocalDate.now( z ).plusDays( 6 )

Compare. Let's simplify your branching logic. We will work chronologically in reverse order through five cases: future, today, past six days, prior, impossible.

if( ldInput.ifAfter( today ) ) {
    System.out.println( "ERROR - input is in the future. Not expected." ) ;
} else if( ldInput.isEqual( today ) ) {
    return "Today" ;
} else if ( ! ldInput.isBefore( sixDaysBeforeToday ) ) {  // A shorter way of asking "is equal to OR later" is asking "is NOT before".
    return dowInput.getDisplayName( TextStyle.FULL , Locale.US ) ;  // Let java.time localize the name of the day-of-week.
} else if ( ldInput.isBefore ( sixDaysBeforeToday ) ) {
    return ldInput.format( DateTimeFormatter.ofPattern( "dd-MM-uuuu" ) ) ;
} else {
    System.out.println( "ERROR - Reached impossible point." ) ; // Defensive programming. 
}

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date , Calendar , & SimpleDateFormat .

The Joda-Time project, now in maintenance mode , advises migration to the java.time classes.

To learn more, see the Oracle Tutorial . And search Stack Overflow for many examples and explanations. Specification is JSR 310 .

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM