I've a code to get year, month and day for one of my application.
package com.cera.hyperionUtils;
import java.util.*;
public class HypDate {
public static int curdate(int field)
{
//1. Specify integer 1 for YEAR, 2 for MONTH, 5 DAY_OF_MONTH
Calendar c = new GregorianCalendar();
c.setLenient(true); //Allow overflow
//2. Extract and Return result
if (field == 2) {
field = c.get(Calendar.MONTH) + 1;
}
return c.get(field);
}
public static void main(String[] args)
{
System.out.println(HypDate.curdate(2));
}
}
But when i pass 2 it is giving 0 year and day prints correctly.....Also i was trying to make month as double digit. (like 01 for 1)
Can someone please help me....? (I''m very new to java coding)
Rather than returning these one by one, you may just want to use a SimpleDateFormat to format it.
Say I want a date as year-month-day:
// Necessary imports
import java.text.DateFormat;
import java.text.SimpleDateFormat;
// Declare class and stuff before this
public static String getFormattedDate() {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
return df.format(new Date());
}
public static void main(String[] args) {
System.out.println(getFormattedDate());
}
Outputs 2010-10-29
Edit:
Since you just want the month, you can do this:
public static String getFormattedMonth() {
DateFormat df = new SimpleDateFormat("MM");
return df.format(new Date());
}
if (field == 2) {
field = c.get(Calendar.MONTH) + 1;
}
return c.get(field);
You retrieve the correct month as an index and then use that index to retrieve another field that will be unknown and related in how the constants are saved. Just return the value before, without using a second get.
Maybe you meant
if (field == 2) {
field = Calendar.MONTH;
}
return c.get(field) + 1;
but I don't get why you are redefining that constants instead that use the one already provided..
The problem comes from the fact that when you are getting the month information, you call c.get() twice, which you don't want to do. Instead, you should directly return after you get the first value
//1. Specify integer 1 for YEAR, 2 for MONTH, 5 DAY_OF_MONTH
Calendar c = new GregorianCalendar();
c.setLenient(true); //Allow overflow
//2. Extract and Return result
if (field == Calendar.MONTH) {
return c.get(field) + 1; //because Java months are 0-based
} else {
return c.get(field);
}
Related
Please suggest if there is an API support to determine if my time is between 2 LocalTime instances, or suggest a different approach.
I have this entity:
class Place {
LocalTime startDay;
LocalTime endDay;
}
which stores the working day start and end time, i.e. from '9:00' till '17:00', or a nightclub from '22:00' till "5:00".
I need to implement a Place.isOpen() method that determines if the place is open at a given time.
A simple isBefore/isAfter does not work here, because we also need to determine if the end time is on the next day.
Of course, we can compare the start and end times and make a decision, but I want something without additional logic, just a simple between() call. If LocalTime is not sufficient for this purpose, please suggest other.
If I understand correctly, you need to make two cases depending on whether the closing time is on the same day as the opening time (9-17) or on the next day (22-5).
It could simply be:
public static boolean isOpen(LocalTime start, LocalTime end, LocalTime time) {
if (start.isAfter(end)) {
return !time.isBefore(start) || !time.isAfter(end);
} else {
return !time.isBefore(start) && !time.isAfter(end);
}
}
This looks cleaner for me:
if (start.isBefore(end)) {
return start.isBefore(date.toLocalTime()) && end.isAfter(date.toLocalTime());
} else {
return date.toLocalTime().isAfter(start) || date.toLocalTime().isBefore(end);
}
I have refactored #assylias answer so i use int instead of local time as i get open and close hour from api int integer format
public static boolean isOpen(int start, int end, int time) {
if (start>end) {
return time>(start) || time<(end);
} else {
return time>(start) && time<(end);
}
}
public static boolean isOpen(int start, int end) {
SimpleDateFormat sdf = new SimpleDateFormat("HH");
Date resultdate = new Date();
String hour = sdf.format(resultdate);
int time = Integer.valueOf(hour);
if (start>end) {
return time>(start) || time<(end);
} else {
return time>(start) && time<(end);
}
}
If I use:
GregorianCalendar cal = (GregorianCalendar) GregorianCalendar.getInstance();
boolean yearIsLeapYear = cal.isLeapYear(2016);
Then my varialbe yearIsLeapYear is correctly set to true. However, if I use a variable in place of 2016 it doesn't not work.
int year = 2016;
GregorianCalendar cal = (GregorianCalendar) GregorianCalendar.getInstance();
boolean yearIsLeapYear = cal.isLeapYear(year);
Am I missing something or is it not possible to pass a variable into the isLeapyYear() method? In the program I'm writing the value in the year field can change depending on user input and the final algorithm I'm implementing needs to behave differently when the current year is a leap year or the next year is a leap year. I thought this would be simple way to perform the check.
Edit showing full code
Fields are:
private int year;
private boolean yearIsLeapYear , nextYearIsLeapYear, previousYearIsLeapYear;
I have a constructor as follows:
public FirstDayOfSummer(int currentYear) {
year = currentYear;
checkForLeapYears();
}
And the following method which I am calling in the constructor:
private void checkForLeapYears(){
GregorianCalendar cal = (GregorianCalendar) GregorianCalendar.getInstance();
//checking for a leap year using the current value of "year"
if(cal.isLeapYear(year)){
yearIsLeapYear = true;
}
else{
yearIsLeapYear = false;
}
//checking for a leap year using the value of "year" + 1
if(cal.isLeapYear(year + 1){
nextYearIsLeapYear = true;
}
else{
nextYearIsLeapYear = false;
}
//checking for a leap year using the value of "year" - 1
if(cal.isLeapYear(year - 1){
previousYearIsLeapYear = true;
}
else{
previousYearIsLeapYear = false;
}
}
The error was in calling my constructor.
FirstDayOfSummer currentYearFirstDayOfSummer = new FirstDayOfSummer(Calendar.getInstance().get(Calendar.YEAR));
currentYearFirstDayOfSummer.setYear(2015);
I was accidently using the current year in the constructor and then trying to use a mutator method to change it to something else. Because my method to check for a leap year was only being called in the constructor and not also in the mutator it was never updating my booleans!
Thanks for asking good questions!
I'm create a java webapp and I have to create a consecutive number that should starts every month. The idea is to have something like this:
01-0414 / 02-0414 /03-0414 / 04-0414
where the first two digits should be the consecutive number, and the last four digits are the month and year.
I'm using spring 3.2.2 and hibernate 4.2.6. I really appreciate any help about this.
thanks
Well, your question is not clear. But as far as I understand you need help to get the date. You can use Calendar() or Date(), use something like this Calendar.get(Calendar.MONTH)to get the month and year (or simply parse to string and substring where you want).
Regarding the number at the beginning, I will assume (again, since you are not clear) that it is passed as an input. So basically you concatenate that with the "-" and the output of the previous step; the date thingy.
I hope I helped!
If you want to encode your web app string using a sequence number that gets reset to 1 at the beginning of each month, you could use a singleton class instance to hold the month and sequence number state. The code string generator method checks whether the month has changed, and if so, it resets the internal current month to the new month, and resets the effective internal sequence number to 1.
Here is the generator class (see below for an example of how to use it):
public class MySequenceCodeStringGenerator {
private static final int generatorMonth;
private static final int generatorSequenceNumber;
// Create a singleton instance to hold month and sequence number state.
private static final MySequenceCodeStringGenerator INSTANCE = new MySequenceCodeStringGenerator();
private MySequenceCodeStringGenerator() {
generatorMonth = getCurrentMonth();
generatorSequenceNumber = 0;
}
/////////////////////////
// PUBLIC functions:
/////////////////////////
// Get the singleton instance:
public static MySequenceCodeStringGenerator getInstance() {
return INSTANCE;
}
// Get the formatted sequence code string:
public static int getSequenceCodeString {
int sequenceNumber = getSequenceNumber();
Calendar now = Calendar.getInstance();
int year = now.get(Calendar.YEAR);
int month = now.get(Calendar.MONTH);
String yearString = String.valueOf(year);
return String.format( "%02d-%02d%s", sequenceNumber, month+1, yearString.substring(2) );
}
// Get the current month:
private int getCurrentMonth() {
Calendar now = Calendar.getInstance();
return now.get(Calendar.MONTH);
}
// Get the singleton sequence number. Update if this is a new month.
private int getSequenceNumber() {
currentMonth = getCurrentMonth();
if ( currentMonth != generatorMonth ) {
generatorMonth = currentMonth;
generatorSequenceNumber = 0;
}
return ++generatorSequenceNumber;
}
}
Here's an example of how you use the generator class:
String myWebAppString = MySequenceCodeStringGenerator.getInstance().getSequenceCodeString();
I'm about to write lines of some simple math and wanted to make sure that there wasn't some simple high level construct in Joda-Time to do this already.
I have an object that represents a day of the week, an hour of the day, and a minute of the hour. For example "Wednesday at 10:14am".
I want to calculate the number of milliseconds until the next occurrence. For example if now is Thursday at 10:14 it would be 6 days worth of milliseconds. This is because Wednesday has already passed so it will take 6 days to get to the next Wednesday. If now is Wednesday at 10:13.0001 it will be 999.
Is there a high level construct in Joda-Time so I can do this in one or two lines of code or do I need to do the math myself (including edge cases to wrap on stuff like DOW < DOW_NOW).
Thanks!
Here's my novice try that does not yet work to give you some reference:
public MutableDateTime getDateTime() {
MutableDateTime date = MutableDateTime.now();
date.setDayOfWeek(this.day);
date.setHourOfDay(this.hour);
return date;
}
public long getTimeUntilNextFrom( DateTime from ) {
MutableDateTime to = getDateTime();
if (to.isBefore( from )) {
to.setWeekOfWeekyear(from.getWeekOfWeekyear() + 1);
}
return new Interval(from, to).toDurationMillis();
}
You could do something like this:
import org.joda.time.DateTime;
import org.joda.time.DateTimeConstants;
import org.joda.time.Interval;
import org.joda.time.LocalTime;
public class Main {
public static void main(String[] args) {
Interval interval = betweenNowAndNext(DateTimeConstants.MONDAY, new LocalTime(10, 14));
System.out.println(interval.toDurationMillis());
}
public static Interval betweenNowAndNext(int dayOfWeek, LocalTime time) {
DateTime now = DateTime.now();
DateTime closest = time.toDateTime(now).withDayOfWeek(dayOfWeek);
return new Interval(now, closest.isBefore(now) ? closest.plusWeeks(1) : closest);
}
}
I would do it like this:
public class DistanceCalculator {
public long getMillisecondTillNext(int dayOfWeek, int hourOfDay, int minuteOfHour) {
DateTime now = DateTime.now();
DateTime next = DateTime.now().withDayOfWeek(dayOfWeek).withHourOfDay(hourOfDay).withMinuteOfHour(minuteOfHour);
long distance = next.getMillis() - now.getMillis();
return distance > 0 ? distance : week() - distance;
}
private long week() {
return new DateTime(0).plusWeeks(1).getMillis();
}
}
Haven't hear of any readymade method to get this in Joda...
Here's what I came up with on my own. Still, would be nice to have a solution in fewer lines of code. They DayHour is the class I am working with. It contains a day of the week and the hour of the day.
public class DayHour {
int day;
int hour;
public DayHour(int day, int hour) {
this.day = day;
this.hour = hour;
}
public MutableDateTime getDateTime(DateTime base) {
MutableDateTime date = base.toMutableDateTime();
date.setDayOfWeek(this.day);
date.setHourOfDay(this.hour);
return date;
}
public long getTimeUntilNextFrom(DateTime from) {
MutableDateTime to = getDateTime(from);
if (to.isBefore(from)) {
to.setWeekOfWeekyear(from.getWeekOfWeekyear() + 1);
}
return new Interval(from, to).toDurationMillis();
}
}
#Test
public void testDayHour() {
DateTime now = DateTime.now();
DayHour date = new DayHour(now.getDayOfWeek(), now.getHourOfDay());
MutableDateTime yesterday = now.toMutableDateTime();
yesterday.addDays(-1);
assertEquals(TimeUnit.DAYS.toMillis(1), date.getTimeUntilNextFrom(yesterday.toDateTime()));
MutableDateTime tomorrow = now.toMutableDateTime();
tomorrow.addDays(1);
assertEquals(TimeUnit.DAYS.toMillis(6), date.getTimeUntilNextFrom(tomorrow.toDateTime()));
}
Not quite sure what you are doing. But if what you want is a countdown in milliseconds, I would use the Joda-Time Seconds class with its secondsBetween method. Multiply by 1,000 to report approximate milliseconds. On the last second, switch gears to use the .getMillis method if you truly need that.
For example, I have input parameter this format: "04:00-06:00" or "23:00-24:00". Type of parameter - String.
And in my method I must check, that time range in input parameter NOT before current time. How I can do it?
More details:
input time range: "12:00-15:00"
current time: 16:00.
In this case, method must return false.
Another example:
input time range: "10:30-12:10"
current time: 09:51.
method must return true.
Can you please give me some idea or algorithm? How I can implement this method?
First off, you should probably just learn to use Joda time.
That said, since the times are all zero padded, you can just compare strings lexically.
public static boolean inRange(String time, String range) {
return time.compareTo(range.substring(0, 5)) >= 0
&& time.compareTo(range.substring(6)) <= 0;
}
It's good practice to fail fast on malformed inputs.
private static final Pattern VALID_TIME = Pattern.compile("[012][0-9]:[0-5][0-9]");
private static final Pattern VALID_RANGE = Pattern.compile("[012][0-9]:[0-5][0-9]-[012][0-9]:[0-5][0-9]");
and then put an assert at the top of inRange:
assert VALID_TIME.matcher(time).matches() : time
assert VALID_RANGE.matcher(range).matches() : range
EDIT:
If you really need to represent the current time as a Date, then you should compare it this way:
public final class Range {
/** Inclusive as minutes since midnight */
public final int start, end;
public Range(int start, int end) {
assert end >= start;
}
/** #param time in minutes since midnight */
public boolean contains(int time) {
return start <= time && time <= end;
}
public static Range valueOf(String s) {
assert VALID_RANGE.matcher(s).matches() : s;
return new Range(minutesInDay(s.substring(0, 5)),
minutesInDay(s.substring(6));
}
private static int minutesInDay(String time) {
return Integer.valueOf(time.substring(0, 2)) * 60
+ Integer.valueOf(time.substring(3));
}
}
Use Range.valueOf to convert from a String, convert your Date to a number of minutes since midnight in whatever timezone you like using whatever calendar implementation you like, and then use Range.contains.
Date currentDate = new Date();
Date maxDate;
Date minDate;
//Parse range to two substrings
//parse two substrings to [HH, MM]
//for HH && MM parseInt()
//
minDate= new Date.SetHour(HH); minDate.SetMinute(MM);
//repeat for max date
if(currentDate.Before(maxDate) && currentDate.After(minDate))
{
return true;
}
else
return false;