Example usage for org.joda.time DateTime getDayOfWeek

List of usage examples for org.joda.time DateTime getDayOfWeek

Introduction

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

Prototype

public int getDayOfWeek() 

Source Link

Document

Get the day of week field value.

Usage

From source file:eu.itesla_project.entsoe.cases.EntsoeCaseRepository.java

License:Mozilla Public License

private <R> R scanRepository(DateTime date, CaseType type, Country country,
        Function<List<ImportContext>, R> handler) {
    Collection<EntsoeGeographicalCode> geographicalCodes = country != null ? forCountryHacked(country)
            : Collections.singleton(EntsoeGeographicalCode.UX);
    for (EntsoeFormat format : formats) {
        Path formatDir = config.getRootDir().resolve(format.getDirName());
        if (Files.exists(formatDir)) {
            Path typeDir = formatDir.resolve(type.name());
            if (Files.exists(typeDir)) {
                Path dayDir = typeDir.resolve(String.format("%04d", date.getYear()))
                        .resolve(String.format("%02d", date.getMonthOfYear()))
                        .resolve(String.format("%02d", date.getDayOfMonth()));
                if (Files.exists(dayDir)) {
                    List<ImportContext> importContexts = null;
                    for (EntsoeGeographicalCode geographicalCode : geographicalCodes) {
                        Collection<String> forbiddenFormats = config.getForbiddenFormatsByGeographicalCode()
                                .get(geographicalCode);
                        if (!forbiddenFormats.contains(format.getImporter().getFormat())) {
                            for (int i = 9; i >= 0; i--) {
                                String baseName = String.format(
                                        "%04d%02d%02d_%02d%02d_" + type + "%01d_" + geographicalCode.name()
                                                + "%01d",
                                        date.getYear(), date.getMonthOfYear(), date.getDayOfMonth(),
                                        date.getHourOfDay(), date.getMinuteOfHour(), date.getDayOfWeek(), i);
                                ReadOnlyDataSource ds = dataSourceFactory.create(dayDir, baseName);
                                if (importContexts == null) {
                                    importContexts = new ArrayList<>();
                                }//from w  ww.  j  a va2  s.  c  o  m
                                if (format.getImporter().exists(ds)) {
                                    importContexts.add(new ImportContext(format.getImporter(), ds));
                                }
                            }
                        }
                    }
                    if (importContexts != null) {
                        R result = handler.apply(importContexts);
                        if (result != null) {
                            return result;
                        }
                    }
                }
            }
        }
    }
    return null;
}

From source file:gobblin.util.TimeRangeChecker.java

License:Apache License

/**
 * Checks if a specified time is on a day that is specified the a given {@link List} of acceptable days, and that the
 * hours + minutes of the specified time fall into a range defined by startTimeStr and endTimeStr.
 *
 * @param days is a {@link List} of days, if the specified {@link DateTime} does not have a day that falls is in this
 * {@link List} then this method will return false.
 * @param startTimeStr defines the start range that the currentTime can fall into. This {@link String} should be of
 * the pattern defined by {@link #HOUR_MINUTE_FORMAT}.
 * @param endTimeStr defines the start range that the currentTime can fall into. This {@link String} should be of
 * the pattern defined by {@link #HOUR_MINUTE_FORMAT}.
 * @param currentTime is a {@link DateTime} for which this method will check if it is in the given {@link List} of
 * days and falls into the time range defined by startTimeStr and endTimeStr.
 *
 * @return true if the given time is in the defined range, false otherwise.
 *//*  w  w w .  j  av a2 s  .com*/
public static boolean isTimeInRange(List<String> days, String startTimeStr, String endTimeStr,
        DateTime currentTime) {

    if (!Iterables.any(days, new AreDaysEqual(DAYS_OF_WEEK.get(currentTime.getDayOfWeek())))) {
        return false;
    }

    DateTime startTime = null;
    DateTime endTime = null;

    try {
        startTime = HOUR_MINUTE_FORMATTER.withZone(DATE_TIME_ZONE).parseDateTime(startTimeStr);
    } catch (IllegalArgumentException e) {
        throw new IllegalArgumentException(
                "startTimeStr format is invalid, must be of format " + HOUR_MINUTE_FORMAT, e);
    }

    try {
        endTime = HOUR_MINUTE_FORMATTER.withZone(DATE_TIME_ZONE).parseDateTime(endTimeStr);
    } catch (IllegalArgumentException e) {
        throw new IllegalArgumentException(
                "endTimeStr format is invalid, must be of format " + HOUR_MINUTE_FORMAT, e);
    }

    startTime = startTime.withDate(currentTime.getYear(), currentTime.getMonthOfYear(),
            currentTime.getDayOfMonth());
    endTime = endTime.withDate(currentTime.getYear(), currentTime.getMonthOfYear(),
            currentTime.getDayOfMonth());

    Interval interval = new Interval(startTime.getMillis(), endTime.getMillis(), DATE_TIME_ZONE);
    return interval.contains(currentTime.getMillis());
}

From source file:google.registry.rde.PendingDepositChecker.java

License:Open Source License

private static DateTime advanceToDayOfWeek(DateTime date, int dayOfWeek) {
    while (date.getDayOfWeek() != dayOfWeek) {
        date = date.plusDays(1);//from  w w  w. j a v a2  s.  c om
    }
    return date;
}

From source file:influent.server.utilities.ConstrainedDateRange.java

License:MIT License

/**
 * Constructs a date range that is constrained to begin and end on instances of the specified
 * interval, and that is guaranteed to include the range specified.
 * /*from w  w w . j  a  va  2s  .  c o m*/
 * @param start
 * @param interval
 * @param numBins
 */
public ConstrainedDateRange(DateTime start, FL_DateInterval interval, long numBins) {
    super(start.getMillis(), interval, numBins);

    DateTime constrained = start;

    // constrain to start of interval.
    switch (interval) {

    case SECONDS:
        constrained = new DateTime(start.getYear(), start.getMonthOfYear(), start.getDayOfMonth(),
                start.getHourOfDay(), start.getMinuteOfHour(), start.getSecondOfMinute(), DateTimeZone.UTC);
        break;

    case HOURS:
        constrained = new DateTime(start.getYear(), start.getMonthOfYear(), start.getDayOfMonth(),
                start.getHourOfDay(), 0, DateTimeZone.UTC);
        break;

    case DAYS:
        constrained = new DateTime(start.getYear(), start.getMonthOfYear(), start.getDayOfMonth(), 0, 0,
                DateTimeZone.UTC);
        break;

    case WEEKS:
        constrained = new DateTime(start.getYear(), start.getMonthOfYear(), start.getDayOfMonth(), 0, 0,
                DateTimeZone.UTC);

        final int days = start.getDayOfWeek() % 7;
        final long rewindMillis = days * DateTimeConstants.MILLIS_PER_DAY;

        constrained = new DateTime(constrained.getMillis() - rewindMillis, constrained.getZone());

        break;

    case MONTHS:
        constrained = new DateTime(start.getYear(), start.getMonthOfYear(), 1, 0, 0, DateTimeZone.UTC);
        break;

    case QUARTERS:
        constrained = new DateTime(start.getYear(), 1 + 3 * ((start.getMonthOfYear() - 1) / 3), 1, 0, 0,
                DateTimeZone.UTC);
        break;

    case YEARS:
        constrained = new DateTime(start.getYear(), start.getMonthOfYear(), 1, 0, 0, DateTimeZone.UTC);
        break;
    }

    // add an extra partial interval at the end when not large enough.
    if (!start.equals(constrained)) {
        //System.out.println(start + " -> " + constrained);

        setStartDate(constrained.getMillis());
        setNumBins(numBins + 1);
    }
}

From source file:info.culebrasgis.calculadoradefechas.DiaSemanaActivity.java

License:Open Source License

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_dia_semana);

    fechaUsuario = (Button) findViewById(R.id.buttonFechaUsuario);
    fechaUsuario.setOnClickListener(new View.OnClickListener() {
        @Override//w  w  w . j  ava2 s.c  o  m
        public void onClick(View v) {
            DialogFragment newFragment = new DatePickerFragment();
            newFragment.show(getSupportFragmentManager(), "datePicker");
        }
    });

    resultado = (TextView) findViewById(R.id.textViewResultado);

    volver = (Button) findViewById(R.id.buttonVolver);
    volver.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            finish();
        }
    });

    reiniciar = (Button) findViewById(R.id.buttonReiniciar);
    reiniciar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            resultado.setText(R.string.resultado);
            fechaUsuario.setText(R.string.fecha);
        }
    });

    calcular = (Button) findViewById(R.id.buttonCalcular);
    calcular.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            try {
                int dia, mes, anno, diaSemana;
                dia = Integer.parseInt(String.valueOf(fechaUsuario.getText()).substring(0, 2));
                mes = Integer.parseInt(String.valueOf(fechaUsuario.getText()).substring(3, 5));
                anno = Integer.parseInt(String.valueOf(fechaUsuario.getText()).substring(6, 10));

                DateTime fecha = new DateTime(anno, mes, dia, 0, 0);
                diaSemana = fecha.getDayOfWeek();

                Resources res = getResources();
                String[] diasNombres = res.getStringArray(R.array.days_of_week);

                resultado.setText(
                        String.format(getString(R.string.resultado_dia_semana), diasNombres[diaSemana - 1]));
            } catch (Exception e) {
                resultado.setText(R.string.fecha_incorrecta);
            }
        }
    });

}

From source file:io.apiman.gateway.engine.policies.TimeRestrictedAccessPolicy.java

License:Apache License

/**
 * Returns true if the given time matches the day-of-week restrictions specified
 * by the included filter/rule.//w  ww.  j av a 2s.  com
 * @param currentTime
 * @param filter
 */
private boolean matchesDay(DateTime currentTime, TimeRestrictedAccess filter) {
    Integer dayStart = filter.getDayStart();
    Integer dayEnd = filter.getDayEnd();
    int dayNow = currentTime.getDayOfWeek();
    if (dayStart >= dayEnd) {
        return dayNow >= dayStart && dayNow <= dayEnd;
    } else {
        return dayNow <= dayEnd && dayNow <= dayStart;
    }
}

From source file:io.spikex.core.util.CronEntry.java

License:Apache License

public boolean isDefined(final DateTime tm) {

    boolean defined = false;

    int month = tm.getMonthOfYear();
    int day = tm.getDayOfMonth();
    int dow = tm.getDayOfWeek();
    int hour = tm.getHourOfDay();
    int minute = tm.getMinuteOfHour();

    boolean dayDowMatch = true;

    if (!isEveryDay()) {
        dayDowMatch = isDayDefined(day);
    }/*w ww.j  av a 2 s  .c  o  m*/

    if (!isEveryDow()) {
        dayDowMatch = isDowDefined(dow);
    }

    if (!isEveryDay() && !isEveryDow()) {
        dayDowMatch = (isDayDefined(day) || isDowDefined(dow));
    }

    if (isMonthDefined(month) && dayDowMatch && isHourDefined(hour) && isMinuteDefined(minute)) {

        defined = true;
    }
    //        System.out.println("Defined " + defined + " - month: " + month + " day: " + day + " dow: " + dow
    //                +" hour: " + hour + " minute: " + minute + " dayOrDowMatch: " + dayDowMatch);
    //        System.out.println("dayDowMatch: " + dayDowMatch + " isMonthDefined: " + isMonthDefined(month) 
    //                + " isHourDefined: " + isHourDefined(hour) + " isMinuteDefined: " + isMinuteDefined(minute));
    return defined;
}

From source file:io.warp10.script.functions.TSELEMENTS.java

License:Apache License

@Override
public Object apply(WarpScriptStack stack) throws WarpScriptException {

    Object obj = stack.peek();/*from w  w w.  j a  v a 2  s .com*/

    String tz = null;

    if (obj instanceof String) {
        tz = (String) obj;
        stack.pop();
    } else if (!(obj instanceof Long)) {
        throw new WarpScriptException(getName() + " operates on a timestamp or a timestamp + timezone.");
    }

    DateTimeZone dtz = this.tzones.get(tz);

    if (null == dtz) {
        dtz = DateTimeZone.forID(null == tz ? "UTC" : tz);
        this.tzones.put(tz, dtz);
    }

    obj = stack.pop();

    if (!(obj instanceof Long)) {
        throw new WarpScriptException(getName() + " operates on a timestamp or a timestamp + timezone.");
    }

    long ts = (long) obj;

    // Convert ts to milliseconds

    long tsms = ts / Constants.TIME_UNITS_PER_MS;

    DateTime dt = new DateTime(tsms, dtz);

    // Extract components into an array

    List<Long> elements = new ArrayList<Long>();

    elements.add((long) dt.getYear());
    elements.add((long) dt.getMonthOfYear());
    elements.add((long) dt.getDayOfMonth());
    elements.add((long) dt.getHourOfDay());
    elements.add((long) dt.getMinuteOfHour());
    elements.add((long) dt.getSecondOfMinute());
    elements.add(ts % Constants.TIME_UNITS_PER_S);
    elements.add((long) dt.getDayOfYear());
    elements.add((long) dt.getDayOfWeek());
    elements.add((long) dt.getWeekOfWeekyear());

    stack.push(elements);

    return stack;
}

From source file:io.warp10.script.mapper.MapperDayOfWeek.java

License:Apache License

@Override
public Object apply(Object[] args) throws WarpScriptException {
    long tick = (long) args[0];
    long[] locations = (long[]) args[4];
    long[] elevations = (long[]) args[5];

    long location = locations[0];
    long elevation = elevations[0];

    DateTime dt = new DateTime(tick / Constants.TIME_UNITS_PER_MS, this.dtz);

    return new Object[] { tick, location, elevation, dt.getDayOfWeek() };
}

From source file:isjexecact.br.com.inso.utils.Funcoes.java

/**
 * Retorna um nmero correspondente ao dia da semana que vai variar de 0  7,
 * sendo que zero em caso de erro ou data invlida.
 * Retorna 1 para domingo, 2 para segunda... e 7 para sbado.
 * @param data Data a ser analisada./*  w ww  .  jav a2 s .c o m*/
 * @return Nmero correspondendo o dia da semana.
 */
public static int getDow(Date data) {
    if (data == null) {
        return 0;
    }
    // Glauber 11/09/2014 - Estou trocando pelo componente joda-time para me livrar da dor de cabea de utiilzar as classes nativa do Java.
    DateTime dateTime = new DateTime(data);
    return dateTime.getDayOfWeek();

    //        Calendar calendario = new GregorianCalendar();    
    //        calendario.setTime(data);
    //        return calendario.get(Calendar.DAY_OF_WEEK) ;
}