@param $str
@param \DateTimeZone|string $tz

@return int

@throws \Exception
544768
final public static function asJavaScriptTimestamp($str, $tz = 'UTC')
    {
        $datePart = $str;
        $msPart = 0;
        if (strpos($str, '.') !== false) {
            $parts = explode('.', $str);
            $datePart = $parts[0];
            $msPart = str_pad($parts[1], 6, '0', STR_PAD_RIGHT);
        }

        return self::asTimestamp($datePart, $tz) * 1000 + intval(intval($msPart) / 1000);
    }
1263304
def convert_timezone(date_str, tz_from, tz_to="UTC", fmt=None):
    
    tz_offset = datetime_to_timezone(
        datetime.datetime.now(), tz=tz_from).strftime('%z')
    tz_offset = tz_offset[:3] + ':' + tz_offset[3:]

    date = parse_date(str(date_str) + tz_offset)
    if tz_from != tz_to:
        date = datetime_to_timezone(date, tz_to)

    if isinstance(fmt, str):
        return date.strftime(fmt)
    return date
1319833
public static function isAlphaNum($str)
    {
        if (!is_string($str)) {
            throw new \ErrorException('Accept string ' . gettype($str) . ' given');
        }

        return (bool) preg_match('/^[a-zA-Z0-9]+$/', $str);
    }
48440
public static function chrToInt(string $chr): int
    {
        if (Binary::safeStrlen($chr) !== 1) {
            throw new \RangeException('Must be a string with a length of 1');
        }
        $result = \unpack('C', $chr);
        return (int) $result[1];
    }
626832
function _date2timestamp( $datetime, $tz=null ) {
    $output = null;
    if( !isset( $datetime['hour'] )) $datetime['hour'] = '0';
    if( !isset( $datetime['min'] ))  $datetime['min']  = '0';
    if( !isset( $datetime['sec'] ))  $datetime['sec']  = '0';
    foreach( $datetime as $dkey => $dvalue ) {
      if( 'tz' != $dkey )
        $datetime[$dkey] = (integer) $dvalue;
    }
    if( $tz )
      $datetime['tz'] = $tz;
    $offset = 0;
    if( isset( $datetime['tz'] ) && ( '' < trim ( $datetime['tz'] )))
      $offset = $this->_tz2offset( $datetime['tz'] );
    $output          = mktime( $datetime['hour']
                             , $datetime['min']
                             , $datetime['sec'] + $offset
                             , $datetime['month']
                             , $datetime['day']
                             , $datetime['year'] );
    return $output;
  }
362960
public static long unixTimestamp(String dateStr, String format, TimeZone tz) {
		long ts = parseToTimeMillis(dateStr, format, tz);
		if (ts == Long.MIN_VALUE) {
			return Long.MIN_VALUE;
		} else {
			// return the seconds
			return ts / 1000;
		}
	}
1053471
def timezone_from_str(tz_str):
    
    m = re.match(r'UTC([+|-]\d{1,2}):(\d{2})', tz_str)
    if m:
        # in format 'UTC±[hh]:[mm]'
        delta_h = int(m.group(1))
        delta_m = int(m.group(2)) if delta_h >= 0 else -int(m.group(2))
        return timezone(timedelta(hours=delta_h, minutes=delta_m))

    # in format 'Asia/Shanghai'
    try:
        return pytz.timezone(tz_str)
    except pytz.exceptions.UnknownTimeZoneError:
        return None
1204504
def dtstr_to_datetime(dtstr, to_tz=None, fail_silently=True):
    
    try:
        dt = datetime.datetime.utcfromtimestamp(int(dtstr, 36) / 1e3)
        if to_tz:
            dt = timezone.make_aware(dt, timezone=pytz.UTC)
            if to_tz != pytz.UTC:
                dt = dt.astimezone(to_tz)
        return dt
    except ValueError, e:
        if not fail_silently:
            raise e
        return None
563980
def tz(self):
        """"""

        if self.timezone is None:
            return None

        try:
            tz = pytz.timezone(self.timezone)
            return tz
        except pytz.UnknownTimeZoneError:
            raise AstralError("Unknown timezone '%s'" % self.timezone)
874605
public static function AdjustDateTimeToTimezoneWithTimezone( $arg, $tz )
	{
		if ( $arg instanceof Undefined )
		{
			return Undefined::getValue();
		}

	    /**
	     * @var DateTimeValue $dateTime
	     */
	    $dateTime = $arg;

		if ( $tz instanceof Undefined )
		{
		    $dt = DateTimeValue::fromDate( $dateTime->S, $dateTime->Value, false );
		    $dt->IsLocal = true;
		    return $dt;
		}

	    /**
	     * @var DayTimeDurationValue $duration
	     */
	    $duration = $tz;
		if ( $duration->getHours() > 14 || ( $duration->getHours() == 14 && ( $duration->getMinutes() > 0 || $duration->getSeconds() > 0 ) ) )
		{
			throw XPath2Exception::withErrorCodeAndParam( "FODT0003", Resources::FODT0003, $duration->ToString() );
		}

	    /**
	     * @var \DateTimeZone $dtz
	     */
	   	// Create a Timezone instance from the duration.  'R' is the sign
	    $dtz = new \DateTimeZone( $duration->Value->format( "%R%H:%I" ) );
	    try
		{
	    	if ( $dateTime->IsLocal )
	    	{
	    		$dt = new \DateTime( $dateTime->Value->format( "Y-m-d\TH:i:s" ), $dtz );
				return DateTimeValue::fromDate( $dateTime->S, $dt );
	    	}
	    	else
	    	{
	    		$dt = new \DateTime( $dateTime->Value->format( "Y-m-d\TH:i:sP" ) );
				$dt->setTimezone( $dtz );
				return DateTimeValue::fromDate( $dateTime->S, $dt );
	    	}
		}
		catch ( ArgumentException $ex )
		{
		    throw XPath2Exception::withErrorCodeAndParam( "FODT0003", Resources::FODT0003, $duration->ToString() );
		}
	}
1362755
public static int timeToInternal(java.sql.Time time, TimeZone tz) {
		long ts = time.getTime() + tz.getOffset(time.getTime());
		return (int) (ts % MILLIS_PER_DAY);
	}
200935
public static DateTime toDate(Object o, TimeZone tz) throws PageException {
	return DateCaster.toDateAdvanced(o, tz);
    }
953742
public static function AdjustDateToTimezoneWithTimezone( $arg, $tz )
	{
		if ( $arg instanceof Undefined )
			return Undefined::getValue();

		/**
		 * @var DateValue $date
		 */
		$date = $arg;

		if ( $tz instanceof Undefined )
		{
			$dt = DateValue::Parse( ( $date->S ? "-" : "" ) . $date->Value->format( "Y-m-d" ) );
			$dt->IsLocal = true;
			return $dt;
		}

		/**
		 * @var DayTimeDurationValue $duration
		 */
		$duration = $tz;
		if ( $duration->getHours() > 14 || ( $duration->getHours() == 14 && ( $duration->getMinutes() > 0 || $duration->getSeconds() > 0 ) ) )
		{
			throw XPath2Exception::withErrorCodeAndParam( "FODT0003", Resources::FODT0003, $duration->ToString() );
		}

		/**
		 * @var \DateTimeZone $dtz
		 */
		// Create a Timezone instance from the duration.  'R' is the sign
		$dtz = new \DateTimeZone( $duration->Value->format( "%R%H:%I" ) );

		try
		{
			// Create a new DateTValue instance
			if ( $date->IsLocal )
			{
				$dt = new \DateTime( $date->Value->format( "Y-m-d\TH:i:s" ), $dtz );
				return DateValue::fromDate( $date->S, $dt );
			}
			else
			{
				$dt = new \DateTime( $date->Value->format( "Y-m-d\TH:i:sP" ) );
				$dt->setTimezone( $dtz );
				return DateValue::fromDate( $date->S, $dt );
			}
		}
		catch ( ArgumentException $ex )
		{
			throw XPath2Exception::withErrorCodeAndParam( "FODT0003", Resources::FODT0003, $duration->ToString() );
		}

	}
99649
@SuppressWarnings("unused")
  public static String rfcDateTime(final Date val, final TimeZone tz) {
    synchronized (rfcDateTimeTZFormat) {
      rfcDateTimeTZFormat.setTimeZone(tz);
      return rfcDateTimeTZFormat.format(val);
    }
  }
1008795
public static Date fromRfcDateTime(final String val,
                                     final TimeZone tz) throws BadDateException {
    try {
      synchronized (rfcDateTimeTZFormat) {
        rfcDateTimeTZFormat.setTimeZone(tz);
        return rfcDateTimeTZFormat.parse(val);
      }
    } catch (Throwable t) {
      throw new BadDateException();
    }
  }
1134925
public static function toDateTime($value, DateTimeZone $dtz) : DateTime
    {
        // TODO : Figure out where to move. Can vary for different source objects
        $format = 'Y-m-d H:i:s';

        if (is_string($value)) {
            $val = strtotime($value);
            if (false === $val) {
                throw new InvalidArgumentException(sprintf('Unsupported datetime string provided: %s', $value));
            }

            return new DateTime(date($format, $val), $dtz);
        }

        if ($value instanceof Time) {
            $value = $value->format($format);

            return new DateTime($value, $dtz);
        }

        if ($value instanceof DateTime) {
            return $value;
        }

        throw new InvalidArgumentException("Type [" . gettype($value) . "] is not supported for date/time");
    }
200891
protected function convertTs($str)
    {
        if (empty($str) || strlen($str) != 14) {
            return false;
        }
        $y = (int) substr($str, 0, 4);
        $m = (int) substr($str, 4, 2);
        $d = (int) substr($str, 6, 2);
        $h = (int) substr($str, 8, 2);
        $i = (int) substr($str, 10, 2);
        $s = (int) substr($str, 12, 2);

        $dt = new \DateTime();
        $dt->setTimezone(new \DateTimeZone('UTC'));
        $dt->setDate($y, $m, $d);
        $dt->setTime($h, $i, $s);

        return $dt->getTimestamp();
    }