Skip to content

Commit

Permalink
Switch to using java.time classes & make work for dates past 2038.
Browse files Browse the repository at this point in the history
  • Loading branch information
norrisjeremy committed Jan 19, 2024
1 parent 3a909d0 commit fb55ea1
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 5 deletions.
21 changes: 16 additions & 5 deletions src/main/java/com/jcraft/jsch/SftpATTRS.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,11 @@

package com.jcraft.jsch;

import java.util.Date;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

/*
* uint32 flags uint64 size present only if flag SSH_FILEXFER_ATTR_SIZE uint32 uid present only if
Expand Down Expand Up @@ -122,13 +126,20 @@ else if ((permissions & S_IXGRP) != 0)
}

public String getAtimeString() {
Date date = new Date(((long) atime) * 1000L);
return (date.toString());
return toDateString(Integer.toUnsignedLong(atime));
}

public String getMtimeString() {
Date date = new Date(((long) mtime) * 1000L);
return (date.toString());
return toDateString(Integer.toUnsignedLong(mtime));
}

private static DateTimeFormatter DTF =
DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ROOT);

static String toDateString(long epochSeconds) {
Instant instant = Instant.ofEpochSecond(epochSeconds);
ZonedDateTime zdt = ZonedDateTime.ofInstant(instant, ZoneId.systemDefault());
return DTF.format(zdt);
}

public static final int SSH_FILEXFER_ATTR_SIZE = 0x00000001;
Expand Down
38 changes: 38 additions & 0 deletions src/test/java/com/jcraft/jsch/SftpATTRSTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package com.jcraft.jsch;

import static org.junit.jupiter.api.Assertions.assertEquals;

import java.util.Date;
import java.util.Random;
import org.junit.jupiter.api.Test;

public class SftpATTRSTest {

private final Random random = new Random();

@Test
public void testToDateString0() {
String expected = new Date(0L).toString();
String actual = SftpATTRS.toDateString(0L);
assertEquals(expected, actual);
}

@Test
public void testToDateStringNow() {
long now = System.currentTimeMillis() / 1000L;
String expected = new Date(now * 1000L).toString();
String actual = SftpATTRS.toDateString(now);
assertEquals(expected, actual);
}

@Test
public void testToDateStringRandom() {
for (int i = 0; i < 1000000; i++) {
int j = random.ints(Integer.MIN_VALUE, Integer.MAX_VALUE).findFirst().getAsInt();
long l = Integer.toUnsignedLong(j);
String expected = new Date(l * 1000L).toString();
String actual = SftpATTRS.toDateString(l);
assertEquals(expected, actual);
}
}
}

0 comments on commit fb55ea1

Please sign in to comment.