Home Reference Source

packages/core/src/nativeJs.js

  1. /*
  2. * @copyright (c) 2015-present, Philipp Thürwächter, Pattrick Hüper & js-joda contributors
  3. * @license BSD-3-Clause (see LICENSE in the root directory of this source tree)
  4. */
  5.  
  6. import { requireNonNull } from './assert';
  7. import { IllegalArgumentException } from './errors';
  8. import { Instant, ZoneId } from './js-joda';
  9.  
  10. /**
  11. * Creates ZonedDateTime from a javascript Date or a moment instance.
  12. * @param {!(Date|moment)} date - a javascript Date or a moment instance
  13. * @param {ZoneId} [zone = ZoneId.systemDefault()] - the zone of the returned ZonedDateTime, defaults to ZoneId.systemDefault()
  14. * @returns {ZonedDateTime}
  15. */
  16. export function nativeJs(date, zone = ZoneId.systemDefault()) {
  17. requireNonNull(date, 'date');
  18. requireNonNull(zone, 'zone');
  19. if(date instanceof Date) {
  20. return Instant.ofEpochMilli(date.getTime()).atZone(zone);
  21. } else if(typeof date.toDate === 'function' && date.toDate() instanceof Date) {
  22. return Instant.ofEpochMilli(date.toDate().getTime()).atZone(zone);
  23. }
  24. throw new IllegalArgumentException('date must be a javascript Date or a moment instance');
  25. }