Convert java date to 18 dgit LDAP date
我们有一项要求,我们需要在Active Directory中插入accountExpires日期。
并且AD仅将输入日期作为大整数(18位LDAP日期)。
我有一个格式为
请让我知道如何转换以下格式,并用当前日期格式填充广告。
这是基于JDK的解决方案
1 2 3 4 5 6 7 |
根据此处定义,这是使用Joda Time的解决方案:
The timestamp is the number of 100-nanoseconds intervals (1 nanosecond = one billionth of a second) since Jan 1, 1601 UTC.
样例代码:
1 2 3 4 5 6 7 8 9 10 11 12 | public final class Foo { private static final DateTime LDAP_START_DATE = new DateTime(1601, 1, 1, 0, 0, DateTimeZone.UTC); public static void main(final String... args) { final DateTime now = DateTime.now(); final Interval interval = new Interval(LDAP_START_DATE, now); System.out.println(interval.toDurationMillis() * 10000); } } |
将此代码中的
我花了一段时间使用java.time API编写LDAP时间戳转换器
(Java 8)。
也许这个小工具可以帮助像我这样的人(当我寻找合适的解决方案时,我一直在这里:)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | import java.time.*; public class LdapTimestampUtil { /** * Microsoft world exist since since Jan 1, 1601 UTC */ public static final ZonedDateTime LDAP_MIN_DATE_TIME = ZonedDateTime.of(1601, 1, 1, 0, 0, 0, 0, ZoneId.of("UTC")); public static long instantToLdapTimestamp(Instant instant) { ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(instant, ZoneOffset.UTC); return zonedDateToLdapTimestamp(zonedDateTime); } public static long localDateToLdapTimestamp(LocalDateTime dateTime) { ZonedDateTime zonedDateTime = dateTime.atZone(ZoneId.systemDefault()); return zonedDateToLdapTimestamp(zonedDateTime); } public static long zonedDateToLdapTimestamp(ZonedDateTime zonedDatetime) { Duration duration = Duration.between(LDAP_MIN_DATE_TIME, zonedDatetime); return millisecondsToLdapTimestamp(duration.toMillis()); } /** * The LDAP timestamp is the number of 100-nanoseconds intervals since since Jan 1, 1601 UTC */ private static long millisecondsToLdapTimestamp(long millis) { return millis * 1000 * 10; } } |
我已经在GitHub上发布了完整的工具:
https://github.com/PolishAirports/ldap-utils
这对我来说很好:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | static String parseLdapDate(String ldapDate) { long nanoseconds = Long.parseLong(ldapDate); // nanoseconds since target time that you want to convert to java.util.Date long mills = (nanoseconds / 10000000); long unix = (((1970 - 1601) * 365) - 3 + Math.round((1970 - 1601) / 4)) * 86400L; long timeStamp = mills - unix; Date date = new Date(timeStamp * 1000L); // *1000 is to convert seconds to milliseconds SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z"); // the format of your date // sdf.setTimeZone(TimeZone.getTimeZone("GMT")); // give a timezone reference for formating (see comment at the bottom String formattedDate = sdf.format(date); return formattedDate; } |