diff --git a/src/main/java/com/jcraft/jsch/SftpATTRS.java b/src/main/java/com/jcraft/jsch/SftpATTRS.java index 84151085..cff4c660 100644 --- a/src/main/java/com/jcraft/jsch/SftpATTRS.java +++ b/src/main/java/com/jcraft/jsch/SftpATTRS.java @@ -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 @@ -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; diff --git a/src/test/java/com/jcraft/jsch/SftpATTRSTest.java b/src/test/java/com/jcraft/jsch/SftpATTRSTest.java new file mode 100644 index 00000000..d8359204 --- /dev/null +++ b/src/test/java/com/jcraft/jsch/SftpATTRSTest.java @@ -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); + } + } +}