Example usage for org.joda.time Period Period

List of usage examples for org.joda.time Period Period

Introduction

In this page you can find the example usage for org.joda.time Period Period.

Prototype

private Period(int[] values, PeriodType type) 

Source Link

Document

Constructor used when we trust ourselves.

Usage

From source file:com.twigasoft.settings.ClockInOut.java

public boolean checkClockInstance(String type, String status) {
    Connection conn = null;/*w  ww.ja  va  2  s  .  c  o  m*/
    PreparedStatement pst = null;
    ResultSet rs = null;
    String sql = "SELECT create_time FROM tbl_clocking WHERE emp_id=? AND type=? AND status=?";
    Timestamp stamp = null;
    try {
        conn = Database.getConnection();
        pst = conn.prepareStatement(sql);
        pst.setInt(1, app.getEmpId());
        pst.setString(2, type);
        pst.setString(3, status);
        rs = pst.executeQuery();
        while (rs.next()) {
            stamp = rs.getTimestamp(1);
            DateTime timestamp = new DateTime(new Date(stamp.getTime()));
            DateTime now = new DateTime(new Date().getTime());
            Period period = new Period(timestamp, now);
            if (period.getDays() == 0) {
                return true;
            }
        }

    } catch (SQLException ex) {
        ex.printStackTrace();
    } finally {
        try {
            rs.close();
            pst.close();
            conn.close();

        } catch (SQLException ex) {
            Logger.getLogger(ClockInOut.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    return false;
}

From source file:com.twigasoft.templates.MinimalWorkingExample.java

public static String getTimestampDiff(Timestamp t) {
    final DateTime start = new DateTime(date.getTime());
    final DateTime end = new DateTime(t);
    Period p = new Period(start, end);
    PeriodFormatter formatter = new PeriodFormatterBuilder().printZeroAlways().minimumPrintedDigits(2)
            .appendYears().appendSuffix(" year", " years").appendSeparator(", ").appendMonths()
            .appendSuffix(" month", " months").appendSeparator(", ").appendDays().appendSuffix(" day", " days")
            .appendSeparator(" and ").appendHours().appendLiteral(":").appendMinutes().appendLiteral(":")
            .appendSeconds().toFormatter();
    return p.toString(formatter);
}

From source file:control.ConfigController.java

public static boolean doDailyBackup() {
    cdao = new ConfigDAO();
    if (cdao.isSetAutoBackup()) {
        dao = new GenericDAO();
        String s = dao.get("app_config", "last_backup");
        LocalDateTime hoje = new LocalDateTime(System.currentTimeMillis());
        LocalDateTime last_bkp = new LocalDateTime(s);
        Period p = new Period(hoje, last_bkp);
        if ((p.getDays() < 0) || (s == null)) {
            java.io.File file = new java.io.File(
                    System.getProperty("user.home") + System.getProperty("file.separator") + ".jbiblioteca"
                            + System.getProperty("file.separator") + "jbiblioteca_bkp.db");
            try {
                Database.backupDatabase(file);
                ConfigController.saveLastBackupDate("'" + hoje.toString() + "'");
                System.out.println("Backup \"" + file.getCanonicalPath() + "\" salvo. ");
            } catch (Exception ex) {
                Logger.getLogger(ConfigController.class.getName()).log(Level.SEVERE, null, ex);
            }/*  www. j av a  2  s  .c o  m*/
            return true;
        }
    }
    return false;
}

From source file:control.EmprestimoController.java

private static TableModel UpdateTablemodel(TableModel tb) {
    LocalDateTime hoje = new LocalDateTime(System.currentTimeMillis());
    for (int i = 0; i < tb.getRowCount(); i++) {
        String in = tb.getValueAt(i, 3).toString();
        String out = tb.getValueAt(i, 4).toString();
        LocalDateTime inicio = new LocalDateTime(in);
        LocalDateTime fim = new LocalDateTime(out);
        tb.setValueAt("" + inicio.getDayOfMonth() + "/" + inicio.getMonthOfYear() + "/" + inicio.getYear() + "",
                i, 3);/*from   w  w w  .  j  av  a 2  s . co m*/
        tb.setValueAt("" + fim.getDayOfMonth() + "/" + fim.getMonthOfYear() + "/" + fim.getYear() + "", i, 4);

        Period p = new Period(hoje, fim);
        int dias = p.getDays();
        int horas = p.getHours();
        int month = p.getMonths();
        //System.out.println(dias+":"+horas+" :: ENTRE AS DATAS "+fim.toString()+" :: "+hoje.toString());
        if (dias < 1) {
            if (dias == 0) {
                tb.setValueAt("Atraso " + horas * -1 + "h", i, 5);
                if (horas > 0)
                    tb.setValueAt("Restam " + horas + "h", i, 5);
            } else
                tb.setValueAt("Atraso " + dias * -1 + "d:" + horas * -1 + "h", i, 5);

        }
        /*else 
        if (month >= 0)
            tb.setValueAt("Restam "+dias+"d:"+horas+"h", i, 5); 
        else
            tb.setValueAt("Restam "+month+" meses", i, 5); */
    }
    return tb;
}

From source file:cz.cesnet.shongo.client.web.models.RoomModel.java

/**
 * Constructor./*from  w  ww  .  j  a va 2 s .co  m*/
 *
 * @param roomExecutable    to initialize the {@link RoomModel} from
 * @param cacheProvider     which can be used for initializing
 * @param messageProvider   sets the {@link #messageProvider}
 * @param executableService which can be used for initializing
 * @param userSession       which can be used for initializing
 * @param services          specifies whether {@link #recordingService} should be loaded
 */
public RoomModel(AbstractRoomExecutable roomExecutable, CacheProvider cacheProvider,
        MessageProvider messageProvider, ExecutableService executableService, UserSession userSession,
        boolean services) {
    SecurityToken securityToken = cacheProvider.getSecurityToken();

    // Setup room
    this.messageProvider = messageProvider;
    this.id = roomExecutable.getId();
    this.slot = roomExecutable.getOriginalSlot();
    Interval slot = roomExecutable.getSlot();
    this.slotBefore = null;
    if (!slot.getStart().equals(this.slot.getStart())) {
        this.slotBefore = new Period(slot.getStart(), this.slot.getStart());
    }
    this.slotAfter = null;
    if (!slot.getEnd().equals(this.slot.getEnd())) {
        this.slotAfter = new Period(this.slot.getEnd(), slot.getEnd());
    }
    this.technology = TechnologyModel.find(roomExecutable.getTechnologies());
    this.aliases = roomExecutable.getAliases();
    for (Alias alias : roomExecutable.getAliases()) {
        if (alias.getType().equals(AliasType.ROOM_NAME)) {
            this.name = alias.getValue();
            break;
        }
    }
    loadRoomSettings(roomExecutable);

    // Add room participants from used executable
    if (roomExecutable instanceof UsedRoomExecutable) {
        UsedRoomExecutable usageExecutable = (UsedRoomExecutable) roomExecutable;
        AbstractRoomExecutable usedExecutable = (AbstractRoomExecutable) cacheProvider
                .getExecutable(usageExecutable.getReusedRoomExecutableId());
        RoomExecutableParticipantConfiguration participants = usedExecutable.getParticipantConfiguration();
        for (AbstractParticipant participant : participants.getParticipants()) {
            addParticipant(new Participant(usedExecutable.getId(), participant, cacheProvider));
        }
    }

    // Add room participants from executable
    for (AbstractParticipant participant : roomExecutable.getParticipantConfiguration().getParticipants()) {
        addParticipant(new Participant(this.id, participant, cacheProvider));
    }

    // Room type and license count and active usage
    this.licenseCount = roomExecutable.getLicenseCount();
    this.hasRecordingService = roomExecutable.hasRecordingService();
    this.hasRecordings = roomExecutable.hasRecordings();
    if (this.licenseCount == 0) {
        this.type = RoomType.PERMANENT_ROOM;

        // Get license count from active usage
        ExecutableListRequest usageRequest = new ExecutableListRequest();
        usageRequest.setSecurityToken(securityToken);
        usageRequest.setRoomId(this.id);
        usageRequest.setSort(ExecutableListRequest.Sort.SLOT);
        usageRequest.setSortDescending(true);
        ListResponse<ExecutableSummary> usageSummaries = executableService.listExecutables(usageRequest);
        for (ExecutableSummary usageSummary : usageSummaries) {
            Interval usageSlot = usageSummary.getSlot();
            if (usageSummary.getState().isAvailable()) {
                UsedRoomExecutable usage = (UsedRoomExecutable) cacheProvider
                        .getExecutable(usageSummary.getId());
                this.licenseCount = usage.getLicenseCount();
                this.licenseCountUntil = usageSlot.getEnd();
                this.usageId = usage.getId();
                this.usageState = usage.getState();
                RoomExecutableParticipantConfiguration participants = usage.getParticipantConfiguration();
                for (AbstractParticipant participant : participants.getParticipants()) {
                    addParticipant(new Participant(this.usageId, participant, cacheProvider));
                }
                loadRoomSettings(usage);
                if (services) {
                    this.recordingService = getRecordingService(executableService, securityToken, this.usageId);
                    this.hasRecordingService = this.recordingService != null;
                }
                break;
            }
        }
    } else {
        // Capacity or ad-hoc room
        if (roomExecutable instanceof UsedRoomExecutable) {
            this.type = RoomType.USED_ROOM;
        } else {
            this.type = RoomType.ADHOC_ROOM;
        }
        if (services) {
            this.recordingService = getRecordingService(executableService, securityToken, this.id);
            this.hasRecordingService = this.recordingService != null;
        }
    }

    // Room state
    this.state = RoomState.fromRoomState(roomExecutable.getState(), roomExecutable.getLicenseCount(),
            usageState);
    if (!this.state.isAvailable() && userSession.isAdministrationMode()) {
        this.stateReport = roomExecutable.getStateReport().toString(messageProvider.getLocale(),
                messageProvider.getTimeZone());
    }
}

From source file:de.tshw.worktracker.view.SimpleConsoleView.java

License:MIT License

@Override
public void update(WorkTracker workTracker) {
    LocalDateTime startTime = workTracker.getCurrentLogEntry().getStartTime();
    Period timeElapsed = new Period(startTime, LocalDateTime.now());
    PeriodFormatter formatter = new PeriodFormatterBuilder().appendDays().appendSuffix("d").appendPrefix(" ")
            .appendHours().appendSuffix("h").appendPrefix(" ").appendMinutes().appendSuffix("m")
            .appendPrefix(" ").appendSeconds().appendSuffix("s").toFormatter();
    String formattedTimeElapsed = formatter.print(timeElapsed);
    if (formattedTimeElapsed.equals("")) {
        formattedTimeElapsed = " 0s";
    }/*from   w w  w.  j  a  v  a 2  s  . co m*/
    System.out.print("\rCurrent Project: " + workTracker.getCurrentLogEntry().getProject() + " - Time elapsed: "
            + formattedTimeElapsed);
}

From source file:de.tshw.worktracker.view.TimeEntriesTableModel.java

License:MIT License

public String update(WorkTracker workTracker) {
    int oldProjectCount = elapsedTimes.size();
    HashMap<Project, MutablePeriod> newTimes = new HashMap<>();
    for (Project p : workTracker.getProjects()) {
        newTimes.put(p, new MutablePeriod());
    }// ww  w . j a  va  2s.c  o  m
    MutablePeriod totalTimeToday = new MutablePeriod();
    for (WorkLogEntry entry : workTracker.getTodaysWorkLogEntries()) {
        if (!newTimes.containsKey(entry.getProject())) {
            newTimes.put(entry.getProject(), new MutablePeriod());
        }
        if (entry.getStartTime().toLocalDate().toDateTimeAtStartOfDay()
                .equals(LocalDate.now().toDateTimeAtStartOfDay())) {
            newTimes.get(entry.getProject()).add(entry.getTimeElapsed());
            if (!entry.getProject().equals(workTracker.getPauseProject())) {
                totalTimeToday.add(entry.getTimeElapsed());
            }
        }
    }
    WorkLogEntry entry = workTracker.getCurrentLogEntry();
    Period period = new Period(entry.getStartTime(), LocalDateTime.now());
    newTimes.get(entry.getProject()).add(period);
    if (!entry.getProject().equals(workTracker.getPauseProject())) {
        totalTimeToday.add(period);
    }

    for (Project p : newTimes.keySet()) {
        elapsedTimes.put(p, newTimes.get(p).toPeriod());
    }

    this.totalTimeElapsedToday = totalTimeToday.toPeriod();
    if (oldProjectCount == elapsedTimes.size()) {
        this.fireTableRowsUpdated(0, elapsedTimes.size());
    } else {
        this.fireTableDataChanged();
    }

    return periodFormatter.print(this.totalTimeElapsedToday.normalizedStandard());
}

From source file:edu.isi.misd.scanner.network.base.utils.MessageUtils.java

License:Apache License

public static String formatEventDuration(Calendar start, Calendar end) {
    if (end.before(start)) {
        throw new RuntimeException("Event start time was after event end time");
    }/*from www . j a  va  2  s  . co m*/

    Period period = new Period(start.getTimeInMillis(), end.getTimeInMillis());

    PeriodFormatter pf = new PeriodFormatterBuilder().appendYears().appendSuffix("Y").appendSeparator("-")
            .appendMonths().appendSuffix("M").appendSeparator("-").appendWeeks().appendSuffix("W")
            .appendSeparator("-").appendDays().appendSuffix("D").appendSeparator(" ").appendHours()
            .appendSuffix("h").appendSeparator(":").appendMinutes().appendSuffix("m").appendSeparator(":")
            .appendSecondsWithMillis().appendSuffix("s").printZeroRarelyLast().toFormatter();

    return pf.print(period);
}

From source file:edu.uiowa.icts.bluebutton.json.DateRange.java

License:Apache License

@JsonIgnore
public boolean isActiveIntheLastYear() {
    if (this.end == null && this.start != null) {
        DateTime now = new DateTime();
        DateTime startDateTime = PARSER_FORMAT.parseDateTime(this.start);
        Period period = new Period(startDateTime, now);
        if (period.getYears() > 0) {
            return false;
        } else {//from w  w  w  .  j ava 2  s. c  o  m
            return true;
        }
    } else {
        return false;
    }
}

From source file:ee.ut.soras.test_ajavt.KiiruseTestiTulemus.java

License:Open Source License

private String convertToOtherFields(double timeInMills) {
    Period p = new Period((long) timeInMills, PeriodType.millis());
    p = p.normalizedStandard();// www. j  a va  2s . c  o  m
    DurationFieldType[] fieldTypes = p.getFieldTypes();
    int[] values = p.getValues();
    if (values.length == fieldTypes.length) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < values.length; i++) {
            if (values[i] != 0) {
                sb.append(values[i] + " " + fieldTypes[i].getName() + " ");
            }
        }
        return sb.toString();
    }
    return p.toString();
}