Example usage for org.joda.time DateTime getMonthOfYear

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

Introduction

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

Prototype

public int getMonthOfYear() 

Source Link

Document

Get the month of year field value.

Usage

From source file:edu.wpi.cs.wpisuitetng.modules.cal.ui.navigation.MiniMonth.java

License:Open Source License

public MiniMonth(DateTime time, final MiniCalendarHostIface mc, boolean monthOnly) {
    this.setLayout(new GridLayout(7, 7));
    MutableDateTime prevMonth = new MutableDateTime(time);
    prevMonth.setDayOfMonth(1);/* ww w .  j av  a 2 s. c  o  m*/
    prevMonth.addMonths(-1); // What is prevMonth for?
    String[] dayLabel = { "S", "M", "T", "W", "R", "F", "S" };

    MouseListener monthChanger = new MouseListener() {
        @Override
        public void mouseClicked(MouseEvent me) {
        }

        @Override
        public void mouseEntered(MouseEvent me) {
        }

        @Override
        public void mouseExited(MouseEvent me) {
        }

        @Override
        public void mousePressed(MouseEvent me) {
        }

        @Override
        public void mouseReleased(MouseEvent me) {
            DayLabel d = (DayLabel) (me.getSource());
            if (!(d instanceof DescriptiveDayLabel)) {
                mc.display(d.getMonth());
            }
        }
    };

    MutableDateTime referenceDay = new MutableDateTime(time);
    // reset to the first of the month at midnight, then find Sunday
    referenceDay.setDayOfMonth(1);
    referenceDay.setMillisOfDay(0);
    int first = referenceDay.getDayOfWeek();
    referenceDay.addDays(-first);
    boolean flipFlop = false;

    // add day labels
    for (int i = 0; i < 7; i++) {
        DayLabel day = new DescriptiveDayLabel(dayLabel[i], time);
        day.borderize((i % 7) == 0, i >= 5 * 7, (i % 7) == 6);
        add(day);
        day.addMouseListener(monthChanger);
    }

    // generate days, 6*7 covers all possible months, so we just loop
    // through and add each day
    for (int i = 0; i < (6 * 7); i++) {
        DayLabel day;
        if (monthOnly || MainPanel.getInstance().getView() == ViewSize.Month) {
            if (referenceDay.getDayOfMonth() == 1)
                flipFlop ^= true; // flops the flip flop flappity flip
        } else if (MainPanel.getInstance().getView() == ViewSize.Day)
            flipFlop = referenceDay.getDayOfYear() == time.getDayOfYear()
                    && referenceDay.getYear() == time.getYear();
        else if (MainPanel.getInstance().getView() == ViewSize.Week) {
            if (Months.getWeekStart(time).getMonthOfYear() == 12
                    && Months.getWeekStart(time).getDayOfMonth() >= 26) // Exception case for weeks between years
                flipFlop = time.getMonthOfYear() == 12 ? i >= 35 : i <= 6;
            else
                flipFlop = referenceDay.getDayOfYear() >= Months.getWeekStart(time).getDayOfYear()
                        && referenceDay.getDayOfYear() <= Months.getWeekStart(time).getDayOfYear() + 6;
        }

        if (flipFlop)
            day = new ActiveDayLabel(referenceDay.toDateTime());
        else
            day = new InactiveDayLabel(referenceDay.toDateTime());

        day.borderize((i % 7) == 0, i >= 5 * 7, (i % 7) == 6);
        add(day);
        day.addMouseListener(monthChanger);
        referenceDay.addDays(1); // go to next day
    }
}

From source file:elw.web.FormatTool.java

License:Open Source License

public String format(final long dateLong, String pattern, String patternWeek, String patternToday) {
    final DateTimeFormatter formatter = lookupFormatter(pattern);
    final DateTimeFormatter formatterToday = lookupFormatter(patternToday);
    final DateTimeFormatter formatterWeek = lookupFormatter(patternWeek);

    final DateTime now = new DateTime(System.currentTimeMillis());
    final DateTime midnight = new DateTime(now.getYear(), now.getMonthOfYear(), now.getDayOfMonth(), 0, 0, 0,
            0);//from w  w w  .j ava 2s  . c  o m

    if (midnight.isBefore(dateLong) && midnight.plusDays(1).isAfter(dateLong)) {
        return formatterToday.print(dateLong);
    } else if (now.minusDays(7).isBefore(dateLong) && now.plusDays(7).isAfter(dateLong)) {
        return formatterWeek.print(dateLong);
    } else {
        return formatter.print(dateLong);
    }
}

From source file:es.pode.adl.datamodels.datatypes.DateTimeValidator.java

License:Open Source License

/**
 * Compares two valid data model elements for equality.
 * //from w  w w.j  a v  a 2  s . c  om
 * @param iFirst  The first value being compared.
 * 
 * @param iSecond The second value being compared.
 * 
 * @param iDelimiters The common set of delimiters associated with the
 * values being compared.
 * 
 * @return Returns <code>true</code> if the two values are equal, otherwise
 *         <code>false</code>.
 */
public boolean compare(String iFirst, String iSecond, Vector iDelimiters) {

    boolean equal = true;

    DateTimeFormatter dtp = ISODateTimeFormat.dateTimeParser();

    try {
        // Parse the first string and remove the sub-seconds
        DateTime dt1 = dtp.parseDateTime(iFirst);
        dt1 = new DateTime(dt1.getYear(), dt1.getMonthOfYear(), dt1.getDayOfMonth(), dt1.getHourOfDay(),
                dt1.getMinuteOfHour(), dt1.getSecondOfMinute(), 0);

        // Parse the second string and remove the sub-seconds
        DateTime dt2 = dtp.parseDateTime(iSecond);
        dt2 = new DateTime(dt2.getYear(), dt2.getMonthOfYear(), dt2.getDayOfMonth(), dt2.getHourOfDay(),
                dt2.getMinuteOfHour(), dt2.getSecondOfMinute(), 0);

        equal = dt1.equals(dt2);
    } catch (Exception e) {
        // String format error -- these cannot be equal
        equal = false;
    }

    return equal;
}

From source file:es.ucm.fdi.tutorias.business.boundary.Emails.java

License:Open Source License

private boolean crearArchivoCal(String nombreCalendario, Tutoria tutoria) {
    String hostEmail = username;//from   www.j a v a  2s.  co  m

    //Initialize values
    String calFile = nombreCalendario;
    ;

    //start time
    DateTime comienzo = tutoria.getComienzoTutoria();
    java.util.Calendar startCal = java.util.Calendar.getInstance();
    startCal.set(comienzo.getYear(), comienzo.getMonthOfYear(), comienzo.getDayOfMonth(),
            comienzo.getHourOfDay(), comienzo.getMinuteOfHour());

    //end time
    java.util.Calendar endCal = java.util.Calendar.getInstance();
    DateTime fin = tutoria.getFinTutoria();
    endCal.set(fin.getYear(), fin.getMonthOfYear(), fin.getDayOfMonth(), fin.getHourOfDay(),
            fin.getMinuteOfHour());

    String subject = "Tutora";
    String location = "Location - \"Facultad de Informtica-UCM\"";
    String description = tutoria.getResumenDudas();

    net.fortuna.ical4j.model.Calendar calendar = new net.fortuna.ical4j.model.Calendar();
    calendar.getProperties().add(new ProdId("-//ProyectoSI-FdiUcm//iCal4j 1.0//EN"));
    calendar.getProperties().add(Version.VERSION_2_0);
    calendar.getProperties().add(CalScale.GREGORIAN);

    SimpleDateFormat sdFormat = new SimpleDateFormat("yyyyMMdd'T'hhmmss'Z'");
    String strDate = sdFormat.format(startCal.getTime());

    net.fortuna.ical4j.model.Date startDt = null;
    try {
        startDt = new net.fortuna.ical4j.model.Date(strDate, "yyyyMMdd'T'hhmmss'Z'");
    } catch (ParseException e) {
        e.printStackTrace();
        return false;
    }

    long diff = endCal.getTimeInMillis() - startCal.getTimeInMillis();
    int min = (int) (diff / (1000 * 60));

    Dur dur = new Dur(0, 0, min, 0);

    //Creating a meeting event
    VEvent meeting = new VEvent(startDt, dur, subject);

    meeting.getProperties().add(new Location(location));
    meeting.getProperties().add(new Description());

    try {
        meeting.getProperties().getProperty(Property.DESCRIPTION).setValue(description);
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    } catch (URISyntaxException e) {
        e.printStackTrace();
        return false;
    } catch (ParseException e) {
        e.printStackTrace();
        return false;
    }

    try {
        meeting.getProperties().add(new Organizer("MAILTO:" + hostEmail));
    } catch (URISyntaxException e) {
        e.printStackTrace();
        return false;
    }

    calendar.getComponents().add(meeting);

    FileOutputStream fout = null;

    try {
        fout = new FileOutputStream(calFile);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        return false;
    }

    CalendarOutputter outputter = new CalendarOutputter();
    outputter.setValidating(false);

    try {
        outputter.output(calendar, fout);
        return true;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    } catch (ValidationException e) {
        e.printStackTrace();
        return false;
    }
}

From source file:es.usc.citius.servando.calendula.activities.CalendarActivity.java

License:Open Source License

void setupNewCalendar() {
    caldroidFragment = new CaldroidSampleCustomFragment();
    Bundle args = new Bundle();
    DateTime now = DateTime.now();
    args.putInt(CaldroidFragment.MONTH, now.getMonthOfYear());
    args.putInt(CaldroidFragment.YEAR, now.getYear());
    args.putBoolean(CaldroidFragment.SHOW_NAVIGATION_ARROWS, false);
    args.putBoolean(CaldroidFragment.SIX_WEEKS_IN_CALENDAR, false);
    args.putInt(CaldroidFragment.START_DAY_OF_WEEK, CaldroidFragment.MONDAY);
    args.putInt(CaldroidFragment.THEME_RESOURCE, R.style.CaldroidDefaultNoGrid);
    caldroidFragment.setArguments(args);
    FragmentTransaction t = getSupportFragmentManager().beginTransaction();
    t.replace(R.id.calendar, caldroidFragment);
    t.commit();//  w w w.j a  v  a  2  s .  c  o m

    final CaldroidListener listener = new CaldroidListener() {

        @Override
        public void onSelectDate(Date date, View view) {
            LocalDate d = LocalDate.fromDateFields(date);
            onDaySelected(d);
            if (bestDay != null && bestDay.first != null && bestDay.first.equals(d)) {
                //Toast.makeText(CalendarActivity.this, "Best day!", Toast.LENGTH_SHORT).show();
                AlertDialog.Builder builder = new AlertDialog.Builder(CalendarActivity.this);
                builder.setTitle(R.string.best_date_recommendation_title).setPositiveButton(
                        getString(R.string.driving_warning_gotit), new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
                AlertDialog alertDialog = builder.create();
                alertDialog.setMessage(bestDayText);
                alertDialog.show();
            }
        }

        @Override
        public void onChangeMonth(int month, int year) {
            DateTime date = DateTime.now().withYear(year).withMonthOfYear(month);
            subtitle.setText(date.toString("MMMM YYYY").toUpperCase());
        }

        @Override
        public void onLongClickDate(Date date, View view) {

        }

        @Override
        public void onCaldroidViewCreated() {
            caldroidFragment.getView().findViewById(R.id.calendar_title_view).setVisibility(View.GONE);
            caldroidFragment.getMonthTitleTextView().setVisibility(View.GONE);
        }

    };

    caldroidFragment.setCaldroidListener(listener);
    this.bestDay = pickupUtils.getBestDay();
    this.bestDayText = getBestDayText();

    if (this.bestDay != null && this.bestDay.first != null) {
        //Toast.makeText(CalendarActivity.this, "Best day: " + bestDay.first.toString("dd/MM/YY"), Toast.LENGTH_SHORT).show();
        caldroidFragment.setBackgroundDrawableForDate(
                new ColorDrawable(getResources().getColor(R.color.android_green_light)),
                this.bestDay.first.toDate());
    }

    caldroidFragment.refreshView();
}

From source file:etc.HelperUtils.java

License:Apache License

/**
 * Takes the Timestamp in milis and parses it to the form "yyyy-MM-dd HH:mm" or to "unlimited", if zero
 * //from  w w w . j  a  va2  s  . co m
 * @param ts_Active
 *            the timestamp
 * @return the parsed timestamp
 */
public static String parseStringTs(long ts_Active) {
    if (ts_Active == 0)
        return "unlimited";

    DateTime dt = new DateTime(ts_Active);
    StringBuilder timeString = new StringBuilder();
    // add a leading "0" if the value is under ten
    timeString.append(dt.getYear()).append("-");
    timeString.append(addZero(dt.getMonthOfYear()));
    timeString.append("-");
    timeString.append(addZero(dt.getDayOfMonth()));
    timeString.append(" ");
    timeString.append(addZero(dt.getHourOfDay()));
    timeString.append(":");
    timeString.append(addZero(dt.getMinuteOfHour()));
    return timeString.toString();

}

From source file:eu.cassandra.training.consumption.ConsumptionEventRepo.java

License:Apache License

/**
 * //from   w  w w .ja v a 2 s.  c o m
 * Function for importing consumption events from an file.
 * 
 * @param filename
 *          The name of the file that will be exported.
 * @throws FileNotFoundException
 */
public void readEventsFile(String filename, Installation installation) throws FileNotFoundException {

    int startMinute = 0;
    int endMinute = 0;
    int counter = 0;
    DateTime startDateTime = new DateTime();
    DateTime endDateTime = new DateTime();
    DateTime startDate = new DateTime();
    DateTime endDate = new DateTime();
    DateTime date = installation.getStartDate();

    System.out.println(filename);

    File file = new File(filename);

    Scanner scanner = new Scanner(file);

    String line = scanner.nextLine();
    String[] temp = new String[2];

    while (scanner.hasNext()) {

        line = scanner.nextLine();
        temp = line.split("-");

        startMinute = Integer.parseInt(temp[0]);
        endMinute = Integer.parseInt(temp[1]);

        startDateTime = date.plusMinutes(startMinute);
        endDateTime = date.plusMinutes(endMinute);

        startDate = new DateTime(startDateTime.getYear(), startDateTime.getMonthOfYear(),
                startDateTime.getDayOfMonth(), 0, 0);
        endDate = new DateTime(endDateTime.getYear(), endDateTime.getMonthOfYear(), endDateTime.getDayOfMonth(),
                0, 0);

        if (startDateTime.isAfter(endDateTime) == false)
            events.add(new ConsumptionEvent(counter++, startDateTime, startDate, endDateTime, endDate));
        else
            System.out.println("Start: " + startDateTime + " End: " + endDateTime);

    }

    scanner.close();

    analyze(installation.getStartDate(), installation.getEndDate());

}

From source file:eu.europa.ec.fisheries.uvms.plugins.inmarsat.InmBody.java

License:Open Source License

DateTime getPositionDate(DateTime now) {
    int year = now.getYear();
    int month = now.getMonthOfYear();
    int d = getDayOfMonth();
    int h = getHour();
    int m = getMinutes();

    DateTime dateTime;/*  w  w  w.ja va  2 s.c  om*/
    try {
        // Date is in current month
        dateTime = new DateTime(year, month, d, h, m, DateTimeZone.UTC);
        // Date is in previous month
        if (dateTime.isAfter(now)) {
            dateTime = dateTime.minusMonths(1);
        }
    } catch (IllegalFieldValueException e) {
        // Date is in previous month, and day of month is > days of current month
        if (month != 1) {
            dateTime = new DateTime(year, month - 1, d, h, m, DateTimeZone.UTC);
        }
        // Date is in previous month and previous year (current month is january)
        else {
            dateTime = new DateTime(year - 1, 12, d, h, m, DateTimeZone.UTC);
        }
    }

    return dateTime;

}

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

License:Mozilla Public License

private <R> R scanRepository(DateTime date, CaseType type, Country country,
        Function<List<ImportContext>, R> handler) {
    Collection<UcteGeographicalCode> geographicalCodes = country != null ? forCountryHacked(country)
            : Collections.singleton(UcteGeographicalCode.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 (UcteGeographicalCode 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   ww  w  . j av a2  s. co 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: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<>();
                                }//  ww w  .jav  a 2 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;
}