Esempio n. 1
0
  public static String formatUTCToLocal(String datetime) {
    String returnTimeDate = "";
    DateTime dtUTC = null;
    DateTimeZone timezone = DateTimeZone.getDefault();
    DateTimeFormatter formatDT = DateTimeFormat.forPattern("MMM dd, yyyy  hh:mma");

    try {
      DateTime dateDateTime1 = formatDT.parseDateTime(datetime);
      DateTime now = new DateTime();
      DateTime nowUTC = new LocalDateTime(now).toDateTime(DateTimeZone.UTC);
      long instant = now.getMillis();
      long instantUTC = nowUTC.getMillis();
      long offset = instantUTC - instant;

      // convert to local time
      dtUTC = dateDateTime1.withZoneRetainFields(DateTimeZone.UTC);
      // dtUTC = dateDateTime1.toDateTime(timezone);
      dtUTC = dtUTC.plusMillis((int) offset);

      returnTimeDate = dtUTC.toString(formatDT);
    } catch (Exception e) {
      returnTimeDate = "null";
      e.printStackTrace();
    }
    return returnTimeDate;
  }
Esempio n. 2
0
 private void writeDateTime(
     long readDateTime, final MapOrListWriterImpl writer, String fieldName, boolean isList) {
   DateTime date = new DateTime(readDateTime);
   DateWriter dt;
   if (isList == false) {
     dt = writer.map.date(fieldName);
   } else {
     dt = writer.list.date();
   }
   dt.writeDate(date.withZoneRetainFields(org.joda.time.DateTimeZone.UTC).getMillis());
 }
Esempio n. 3
0
 private void writeTimeStamp(
     int timestamp, final MapOrListWriterImpl writer, String fieldName, boolean isList) {
   DateTime dateTime = new DateTime(timestamp);
   TimeWriter t;
   if (isList == false) {
     t = writer.map.time(fieldName);
   } else {
     t = writer.list.time();
   }
   t.writeTime((int) (dateTime.withZoneRetainFields(org.joda.time.DateTimeZone.UTC).getMillis()));
 }
Esempio n. 4
0
  private static RubyTime createTime(IRubyObject recv, IRubyObject[] args, boolean gmt) {
    Ruby runtime = recv.getRuntime();
    int len = ARG_SIZE;
    Boolean isDst = null;

    DateTimeZone dtz;
    if (gmt) {
      dtz = DateTimeZone.UTC;
    } else if (args.length == 10 && args[9] instanceof RubyString) {
      dtz = getTimeZone(runtime, ((RubyString) args[9]).toString());
    } else {
      dtz = getLocalTimeZone(runtime);
    }

    if (args.length == 10) {
      if (args[8] instanceof RubyBoolean) {
        isDst = ((RubyBoolean) args[8]).isTrue();
      }
      args =
          new IRubyObject[] {
            args[5], args[4], args[3], args[2], args[1], args[0], runtime.getNil()
          };
    } else {
      // MRI accepts additional wday argument which appears to be ignored.
      len = args.length;

      if (len < ARG_SIZE) {
        IRubyObject[] newArgs = new IRubyObject[ARG_SIZE];
        System.arraycopy(args, 0, newArgs, 0, args.length);
        for (int i = len; i < ARG_SIZE; i++) {
          newArgs[i] = runtime.getNil();
        }
        args = newArgs;
        len = ARG_SIZE;
      }
    }

    if (args[0] instanceof RubyString) {
      args[0] = RubyNumeric.str2inum(runtime, (RubyString) args[0], 10, false);
    }

    int year = (int) RubyNumeric.num2long(args[0]);
    int month = 1;

    if (len > 1) {
      if (!args[1].isNil()) {
        IRubyObject tmp = args[1].checkStringType();
        if (!tmp.isNil()) {
          String monthString = tmp.toString().toLowerCase();
          Integer monthInt = MONTHS_MAP.get(monthString);

          if (monthInt != null) {
            month = monthInt;
          } else {
            try {
              month = Integer.parseInt(monthString);
            } catch (NumberFormatException nfExcptn) {
              throw runtime.newArgumentError("Argument out of range.");
            }
          }
        } else {
          month = (int) RubyNumeric.num2long(args[1]);
        }
      }
      if (1 > month || month > 12) {
        throw runtime.newArgumentError("Argument out of range: for month: " + month);
      }
    }

    int[] int_args = {1, 0, 0, 0, 0, 0};

    for (int i = 0; int_args.length >= i + 2; i++) {
      if (!args[i + 2].isNil()) {
        if (!(args[i + 2] instanceof RubyNumeric)) {
          args[i + 2] = args[i + 2].callMethod(runtime.getCurrentContext(), "to_i");
        }

        long value = RubyNumeric.num2long(args[i + 2]);
        if (time_min[i] > value || value > time_max[i]) {
          throw runtime.newArgumentError("argument out of range.");
        }
        int_args[i] = (int) value;
      }
    }

    if (!runtime.is1_9()) {
      if (0 <= year && year < 39) {
        year += 2000;
      } else if (69 <= year && year < 139) {
        year += 1900;
      }
    }

    DateTime dt;
    // set up with min values and then add to allow rolling over
    try {
      dt = new DateTime(year, 1, 1, 0, 0, 0, 0, DateTimeZone.UTC);

      dt =
          dt.plusMonths(month - 1)
              .plusDays(int_args[0] - 1)
              .plusHours(int_args[1])
              .plusMinutes(int_args[2])
              .plusSeconds(int_args[3]);
      if (runtime.is1_9() && !args[5].isNil()) {
        double millis = RubyFloat.num2dbl(args[5]);
        int int_millis = (int) (millis * 1000) % 1000;
        dt = dt.plusMillis(int_millis);
      }

      dt = dt.withZoneRetainFields(dtz);

      // we might need to perform a DST correction
      if (isDst != null) {
        // the instant at which we will ask dtz what the difference between DST and
        // standard time is
        long offsetCalculationInstant = dt.getMillis();

        // if we might be moving this time from !DST -> DST, the offset is assumed
        // to be the same as it was just before we last moved from DST -> !DST
        if (dtz.isStandardOffset(dt.getMillis())) {
          offsetCalculationInstant = dtz.previousTransition(offsetCalculationInstant);
        }

        int offset =
            dtz.getStandardOffset(offsetCalculationInstant)
                - dtz.getOffset(offsetCalculationInstant);

        if (!isDst && !dtz.isStandardOffset(dt.getMillis())) {
          dt = dt.minusMillis(offset);
        }
        if (isDst && dtz.isStandardOffset(dt.getMillis())) {
          dt = dt.plusMillis(offset);
        }
      }
    } catch (org.joda.time.IllegalFieldValueException e) {
      throw runtime.newArgumentError("time out of range");
    }

    RubyTime time = new RubyTime(runtime, (RubyClass) recv, dt);
    // Ignores usec if 8 args (for compatibility with parsedate) or if not supplied.
    if (args.length != 8 && !args[6].isNil()) {
      int usec = int_args[4] % 1000;
      int msec = int_args[4] / 1000;

      if (int_args[4] < 0) {
        msec -= 1;
        usec += 1000;
      }
      time.dt = dt.withMillis(dt.getMillis() + msec);
      time.setUSec(usec);
    }

    time.callInit(IRubyObject.NULL_ARRAY, Block.NULL_BLOCK);
    return time;
  }
Esempio n. 5
0
 public int parseDate(int dateUtc) {
   DateTime dtDate = new DateTime(dateUtc * 1000L);
   DateTime dtEst = dtDate.withZone(DateTimeZone.forID("America/New_York"));
   return (int) (dtEst.withZoneRetainFields(DateTimeZone.UTC).getMillis() / 1000);
 }
Esempio n. 6
0
  /**
   * Parses a UDUNITS time string (of the form "1992-10-8 15:15:42.5 -6:00") and returns a DateTime
   * in the given Chronology.
   *
   * @param baseDateTimeString UDUNITS-formatted time string
   * @param chronology The Chronology (calendar system) in which the time string is to be
   *     interpreted. This must have a time zone of UTC, otherwise an IllegalArgumentException will
   *     be thrown. If this is null, the ISOChronology (in the UTC time zone) will be assumed.
   * @return a DateTime in the given Chronology, with the time zone set to UTC.
   */
  public static DateTime parseUdunitsTimeString(String baseDateTimeString, Chronology chronology) {
    if (chronology == null) chronology = ISOChronology.getInstanceUTC();
    if (!chronology.getZone().equals(DateTimeZone.UTC)) {
      throw new IllegalArgumentException("The time zone of the Chronology must be UTC");
    }

    // Set the defaults for any values that are not specified
    int year = 0;
    int month = 1;
    int day = 1;
    int hour = 0;
    int minute = 0;
    double second = 0.0;

    // We parse the string using a tokenizer to allow for partial strings
    // (e.g. those that contain only the date and not the time)
    StringTokenizer tokenizer = new StringTokenizer(baseDateTimeString, " ");
    try {
      // Parse the date if present
      if (tokenizer.hasMoreTokens()) {
        StringTokenizer dateTokenizer = new StringTokenizer(tokenizer.nextToken(), "-");
        if (dateTokenizer.hasMoreTokens()) year = Integer.parseInt(dateTokenizer.nextToken());
        if (baseDateTimeString.startsWith("-")) {
          /*
           * A '-' was used to denote a negative year.
           */
          year *= -1;
        }
        if (dateTokenizer.hasMoreTokens()) month = Integer.parseInt(dateTokenizer.nextToken());
        if (dateTokenizer.hasMoreTokens()) day = Integer.parseInt(dateTokenizer.nextToken());
      }

      // Parse the time if present
      if (tokenizer.hasMoreTokens()) {
        StringTokenizer timeTokenizer = new StringTokenizer(tokenizer.nextToken(), ":");
        if (timeTokenizer.hasMoreTokens()) hour = Integer.parseInt(timeTokenizer.nextToken());
        if (timeTokenizer.hasMoreTokens()) minute = Integer.parseInt(timeTokenizer.nextToken());
        if (timeTokenizer.hasMoreTokens()) second = Double.parseDouble(timeTokenizer.nextToken());
      }

      // Get a DateTime object in this Chronology
      DateTime dt = new DateTime(year, month, day, hour, minute, 0, 0, chronology);
      // Add the seconds
      dt = dt.plus((long) (1000 * second));

      // Parse the time zone if present
      if (tokenizer.hasMoreTokens()) {
        StringTokenizer zoneTokenizer = new StringTokenizer(tokenizer.nextToken(), ":");
        int hourOffset =
            zoneTokenizer.hasMoreTokens() ? Integer.parseInt(zoneTokenizer.nextToken()) : 0;
        int minuteOffset =
            zoneTokenizer.hasMoreTokens() ? Integer.parseInt(zoneTokenizer.nextToken()) : 0;
        DateTimeZone dtz = DateTimeZone.forOffsetHoursMinutes(hourOffset, minuteOffset);

        // Apply the time zone offset, retaining the field values.  This
        // manipulates the millisecond instance.
        dt = dt.withZoneRetainFields(dtz);
        // Now convert to the UTC time zone, retaining the millisecond instant
        dt = dt.withZone(DateTimeZone.UTC);
      }

      return dt;
    } catch (NumberFormatException nfe) {
      throw new IllegalArgumentException("Illegal base time specification " + baseDateTimeString);
    }
  }