Error with Joda DateTime Formatter - java

I have a class DurationFormatter as below:
import java.util.Date;
import org.joda.time.DateTime;
import org.joda.time.Period;
import org.joda.time.format.PeriodFormatter;
import org.joda.time.format.PeriodFormatterBuilder;
public class DurationFormatter {
private final static PeriodFormatter DURATION_FORMATTER =
new PeriodFormatterBuilder().appendYears()
.appendSuffix("year", "years")
.appendSeparator(" ")
.appendMonths()
.appendSuffix("month", "months")
.appendSeparator(" ")
.appendDays()
.appendSuffix("day", "days")
.appendSeparator(" ")
.appendHours()
.appendSuffix("hour", "hours")
.appendSeparator(" ")
.appendMinutes()
.appendSuffix("minute", "minutes")
.appendSeparator(" ")
.appendSeconds()
.appendSuffix("second", "seconds")
.toFormatter();
public static String format(Date start) {
StringBuffer result = new StringBuffer();
DURATION_FORMATTER.printTo(result,
new Period(new DateTime(start), new DateTime()));
return result.toString();
}
public static String format(Date start, Date end) {
StringBuffer result = new StringBuffer();
DURATION_FORMATTER.printTo(result,
new Period(new DateTime(start),
end == null
? new DateTime()
: new DateTime(end)));
return result.toString();
}
}
And this is my Unit Test:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import junit.framework.Assert;
import org.joda.time.DateTime;
import org.joda.time.Period;
import org.junit.Test;
public class DurationFormatterTest {
#Test
public void testFormatDate() throws ParseException {
int years = 0;
int months = 0;
int weeks = 0;
int days = 0;
int hours = 0;
int minutes = 0;
int seconds = 0;
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
String dateString = "07/27/2010 12:07:34";
Date startDate = (Date) df.parse( dateString );
// Find duration 1
String duration1 = DurationFormatter.format(startDate);
// Parse duration 1 and set values into new Period
String[] tokens = duration1.split("[ ]");
for( int index = 0; index < tokens.length; index++ ) {
String token = tokens[index];
if( token.contains("years") ) {
years = Integer.valueOf(token.replace("years", ""));
System.out.println("Years are: " + years);
}
else if( token.contains("months") ) {
months = Integer.valueOf(token.replace("months", ""));
System.out.println("Months are: " + months);
}
else if( token.contains("days") ) {
days = Integer.valueOf(token.replace("days", ""));
System.out.println("Days are: " + days);
}
else if( token.contains("hours") ) {
hours = Integer.valueOf(token.replace("hours", ""));
}
else if( token.contains("minutes") ) {
minutes = Integer.valueOf(token.replace("minutes", ""));
}
else if( token.contains("seconds") ) {
seconds = Integer.valueOf(token.replace("seconds", ""));
}
}
Period period = new Period( years, months, weeks, days, hours, minutes, seconds, 0);
// User period to initialize new endDate
DateTime endDate = new DateTime(startDate).plus(period);
// Find duration 2 using new endDate
String duration2 = DurationFormatter.format(startDate, endDate.toDate());
// If the durations are the same, then success.
Assert.assertEquals(
"The date of " + duration2
+ " is equal to " + duration1,
duration1, duration2);
}
}
The result always output with error:
junit.framework.ComparisonFailure:
The date of 5days 23hours 5minutes 23seconds is equal to 1month 5days 23hours 5minutes 23seconds expected:<[1month ]5days 23hours 5minut...> but was:<[]5days 23hours 5minut...>
The string '[1month ]' always missing. Please check if I'm missing something in code?
Thanks

In your code, you have .appendSuffix("month", "months") where "month" is the singular form, "months" is the plural form.
Your test only parses the plural forms:
else if( token.contains("months") ) {
...
}
In this case, the test fails because it is only 1 month and therefore singular.
Update your testing code to parse both singular and plural form and it should work!
Documentation

Related

JAVA : calculateFine() in my library management system without using database [duplicate]

I want a Java program that calculates days between two dates.
Type the first date (German notation; with whitespaces: "dd mm yyyy")
Type the second date.
The program should calculates the number of days between the two dates.
How can I include leap years and summertime?
My code:
import java.util.Calendar;
import java.util.Date;
import java.util.Scanner;
public class NewDateDifference {
public static void main(String[] args) {
System.out.print("Insert first date: ");
Scanner s = new Scanner(System.in);
String[] eingabe1 = new String[3];
while (s.hasNext()) {
int i = 0;
insert1[i] = s.next();
if (!s.hasNext()) {
s.close();
break;
}
i++;
}
System.out.print("Insert second date: ");
Scanner t = new Scanner(System.in);
String[] insert2 = new String[3];
while (t.hasNext()) {
int i = 0;
insert2[i] = t.next();
if (!t.hasNext()) {
t.close();
break;
}
i++;
}
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, Integer.parseInt(insert1[0]));
cal.set(Calendar.MONTH, Integer.parseInt(insert1[1]));
cal.set(Calendar.YEAR, Integer.parseInt(insert1[2]));
Date firstDate = cal.getTime();
cal.set(Calendar.DAY_OF_MONTH, Integer.parseInt(insert2[0]));
cal.set(Calendar.MONTH, Integer.parseInt(insert2[1]));
cal.set(Calendar.YEAR, Integer.parseInt(insert2[2]));
Date secondDate = cal.getTime();
long diff = secondDate.getTime() - firstDate.getTime();
System.out.println ("Days: " + diff / 1000 / 60 / 60 / 24);
}
}
UPDATE: The original answer from 2013 is now outdated because some of the classes have been replaced. The new way of doing this is using the new java.time classes.
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd MM yyyy");
String inputString1 = "23 01 1997";
String inputString2 = "27 04 1997";
try {
LocalDateTime date1 = LocalDate.parse(inputString1, dtf);
LocalDateTime date2 = LocalDate.parse(inputString2, dtf);
long daysBetween = Duration.between(date1, date2).toDays();
System.out.println ("Days: " + daysBetween);
} catch (ParseException e) {
e.printStackTrace();
}
Note that this solution will give the number of actual 24 hour-days, not the number of calendar days. For the latter, use
long daysBetween = ChronoUnit.DAYS.between(date1, date2)
Original answer (outdated as of Java 8)
You are making some conversions with your Strings that are not necessary. There is a SimpleDateFormat class for it - try this:
SimpleDateFormat myFormat = new SimpleDateFormat("dd MM yyyy");
String inputString1 = "23 01 1997";
String inputString2 = "27 04 1997";
try {
Date date1 = myFormat.parse(inputString1);
Date date2 = myFormat.parse(inputString2);
long diff = date2.getTime() - date1.getTime();
System.out.println ("Days: " + TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS));
} catch (ParseException e) {
e.printStackTrace();
}
EDIT: Since there have been some discussions regarding the correctness of this code: it does indeed take care of leap years. However, the TimeUnit.DAYS.convert function loses precision since milliseconds are converted to days (see the linked doc for more info). If this is a problem, diff can also be converted by hand:
float days = (diff / (1000*60*60*24));
Note that this is a float value, not necessarily an int.
Simplest way:
public static long getDifferenceDays(Date d1, Date d2) {
long diff = d2.getTime() - d1.getTime();
return TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);
}
In Java 8, you could accomplish this by using LocalDate and DateTimeFormatter. From the Javadoc of LocalDate:
LocalDate is an immutable date-time object that represents a date,
often viewed as year-month-day.
And the pattern can be constructed using DateTimeFormatter. Here is the Javadoc, and the relevant pattern characters I used:
Symbol - Meaning - Presentation - Examples
y - year-of-era - year - 2004; 04
M/L - month-of-year - number/text - 7; 07; Jul;
July; J
d - day-of-month - number - 10
Here is the example:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
public class Java8DateExample {
public static void main(String[] args) throws IOException {
final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd MM yyyy");
final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
final String firstInput = reader.readLine();
final String secondInput = reader.readLine();
final LocalDate firstDate = LocalDate.parse(firstInput, formatter);
final LocalDate secondDate = LocalDate.parse(secondInput, formatter);
final long days = ChronoUnit.DAYS.between(firstDate, secondDate);
System.out.println("Days between: " + days);
}
}
Example input/output with more recent last:
23 01 1997
27 04 1997
Days between: 94
With more recent first:
27 04 1997
23 01 1997
Days between: -94
Well, you could do it as a method in a simpler way:
public static long betweenDates(Date firstDate, Date secondDate) throws IOException
{
return ChronoUnit.DAYS.between(firstDate.toInstant(), secondDate.toInstant());
}
Most / all answers caused issues for us when daylight savings time came around. Here's our working solution for all dates, without using JodaTime. It utilizes calendar objects:
public static int daysBetween(Calendar day1, Calendar day2){
Calendar dayOne = (Calendar) day1.clone(),
dayTwo = (Calendar) day2.clone();
if (dayOne.get(Calendar.YEAR) == dayTwo.get(Calendar.YEAR)) {
return Math.abs(dayOne.get(Calendar.DAY_OF_YEAR) - dayTwo.get(Calendar.DAY_OF_YEAR));
} else {
if (dayTwo.get(Calendar.YEAR) > dayOne.get(Calendar.YEAR)) {
//swap them
Calendar temp = dayOne;
dayOne = dayTwo;
dayTwo = temp;
}
int extraDays = 0;
int dayOneOriginalYearDays = dayOne.get(Calendar.DAY_OF_YEAR);
while (dayOne.get(Calendar.YEAR) > dayTwo.get(Calendar.YEAR)) {
dayOne.add(Calendar.YEAR, -1);
// getActualMaximum() important for leap years
extraDays += dayOne.getActualMaximum(Calendar.DAY_OF_YEAR);
}
return extraDays - dayTwo.get(Calendar.DAY_OF_YEAR) + dayOneOriginalYearDays ;
}
}
The best way, and it converts to a String as bonus ;)
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
//Dates to compare
String CurrentDate= "09/24/2015";
String FinalDate= "09/26/2015";
Date date1;
Date date2;
SimpleDateFormat dates = new SimpleDateFormat("MM/dd/yyyy");
//Setting dates
date1 = dates.parse(CurrentDate);
date2 = dates.parse(FinalDate);
//Comparing dates
long difference = Math.abs(date1.getTime() - date2.getTime());
long differenceDates = difference / (24 * 60 * 60 * 1000);
//Convert long to String
String dayDifference = Long.toString(differenceDates);
Log.e("HERE","HERE: " + dayDifference);
}
catch (Exception exception) {
Log.e("DIDN'T WORK", "exception " + exception);
}
}
Use:
public int getDifferenceDays(Date d1, Date d2) {
int daysdiff = 0;
long diff = d2.getTime() - d1.getTime();
long diffDays = diff / (24 * 60 * 60 * 1000) + 1;
daysdiff = (int) diffDays;
return daysdiff;
}
Java date libraries are notoriously broken. I would advise to use Joda Time. It will take care of leap year, time zone and so on for you.
Minimal working example:
import java.util.Scanner;
import org.joda.time.DateTime;
import org.joda.time.Days;
import org.joda.time.LocalDate;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
public class DateTestCase {
public static void main(String[] args) {
System.out.print("Insert first date: ");
Scanner s = new Scanner(System.in);
String firstdate = s.nextLine();
System.out.print("Insert second date: ");
String seconddate = s.nextLine();
// Formatter
DateTimeFormatter dateStringFormat = DateTimeFormat
.forPattern("dd MM yyyy");
DateTime firstTime = dateStringFormat.parseDateTime(firstdate);
DateTime secondTime = dateStringFormat.parseDateTime(seconddate);
int days = Days.daysBetween(new LocalDate(firstTime),
new LocalDate(secondTime)).getDays();
System.out.println("Days between the two dates " + days);
}
}
String dateStart = "01/14/2015 08:29:58";
String dateStop = "01/15/2015 11:31:48";
//HH converts hour in 24 hours format (0-23), day calculation
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date d1 = null;
Date d2 = null;
d1 = format.parse(dateStart);
d2 = format.parse(dateStop);
//in milliseconds
long diff = d2.getTime() - d1.getTime();
long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000) % 24;
long diffDays = diff / (24 * 60 * 60 * 1000);
System.out.print(diffDays + " days, ");
System.out.print(diffHours + " hours, ");
System.out.print(diffMinutes + " minutes, ");
System.out.print(diffSeconds + " seconds.");
want to get just days(no times) you can use ChronoUnit
ChronoUnit.DAYS.between(date1.toLocalDate(), date2.toLocalDate());
We can make use of LocalDate and ChronoUnit java library, Below code is working fine.
Date should be in format yyyy-MM-dd.
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.*;
class Solution {
public int daysBetweenDates(String date1, String date2) {
LocalDate dt1 = LocalDate.parse(date1);
LocalDate dt2= LocalDate.parse(date2);
long diffDays = ChronoUnit.DAYS.between(dt1, dt2);
return Math.abs((int)diffDays);
}
}
When I run your program, it doesn't even get me
to the point where I can enter the second date.
This is simpler and less error prone.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Test001 {
public static void main(String[] args) throws Exception {
BufferedReader br = null;
br = new BufferedReader(new InputStreamReader(System.in));
SimpleDateFormat sdf = new SimpleDateFormat("dd MM yyyy");
System.out.println("Insert first date : ");
Date dt1 = sdf.parse(br.readLine().trim());
System.out.println("Insert second date : ");
Date dt2 = sdf.parse(br.readLine().trim());
long diff = dt2.getTime() - dt1.getTime();
System.out.println("Days: " + diff / 1000L / 60L / 60L / 24L);
if (br != null) {
br.close();
}
}
}
// date format, it will be like "2015-01-01"
private static final String DATE_FORMAT = "yyyy-MM-dd";
// convert a string to java.util.Date
public static Date convertStringToJavaDate(String date)
throws ParseException {
DateFormat dataFormat = new SimpleDateFormat(DATE_FORMAT);
return dataFormat.parse(date);
}
// plus days to a date
public static Date plusJavaDays(Date date, int days) {
// convert to jata-time
DateTime fromDate = new DateTime(date);
DateTime toDate = fromDate.plusDays(days);
// convert back to java.util.Date
return toDate.toDate();
}
// return a list of dates between the fromDate and toDate
public static List<Date> getDatesBetween(Date fromDate, Date toDate) {
List<Date> dates = new ArrayList<Date>(0);
Date date = fromDate;
while (date.before(toDate) || date.equals(toDate)) {
dates.add(date);
date = plusJavaDays(date, 1);
}
return dates;
}
The following works perfectly well for me:
public int daysBetween(LocalDate later, LocalDate before) {
SimpleDateFormat myFormat = new SimpleDateFormat("dd MM yyyy");
int daysBetween = 0;
try {
Date dateBefore = myFormat.parse(localDateToString(before));
Date dateAfter = myFormat.parse(localDateToString(later));
long difference = dateAfter.getTime() - dateBefore.getTime();
daysBetween = (int) (difference / (1000 * 60 * 60 * 24));
} catch (Exception e) {
e.printStackTrace();
}
return daysBetween;
}
public String localDateToString(LocalDate date) {
DateTimeFormatter myFormat = DateTimeFormatter.ofPattern("dd MM yyyy");
return date.format(myFormat).toString();
}
All the other answers had lots of scary things, here's my simple solution:
public int getDaysDiff(Date dateToCheck)
{
long diffMilliseconds = new Date().getTime() - dateToCheck.getTime();
double diffSeconds = diffMilliseconds / 1000;
double diffMinutes = diffSeconds / 60;
double diffHours = diffMinutes / 60;
double diffDays = diffHours / 24;
return (int) Math.round(diffDays);
}
public class TestCode {
public static void main(String[] args) {
String date1 = "23-04-2021";
String date2 = "24-05-2021";
System.out.println("NDays: " + nDays_Between_Dates(date1, date2));
}
public static int nDays_Between_Dates(String date1, String date2) {
int diffDays = 0;
try {
SimpleDateFormat dates = new SimpleDateFormat("dd-MM-yyyy");
Date startDate = dates.parse(date1);
Date endDate = dates.parse(date2);
long diff = endDate.getTime() - startDate.getTime();
diffDays = (int) (diff / (24 * 60 * 60 * 1000));
} catch (ParseException e) {
e.printStackTrace();
}
return Math.abs(diffDays);
}
}
Output: NDays: 31
public static String dateCalculation(String getTime, String dependTime) {
//Time A is getTime that need to calculate.
//Time B is static time that Time A depend on B Time and calculate the result.
Date date = new Date();
final SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd H:mm:ss");
Date dateObj = null;
Date checkDate = null;
try {
dateObj = sdf.parse(getTime);
} catch (ParseException e) {
e.printStackTrace();
return "0";
}
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
String checkInDate = dateFormat.format(dateObj).toString();
Date defaultTime = null;
try {
defaultTime = dateFormat.parse(dependTime);
checkDate = dateFormat.parse(checkInDate);
} catch (ParseException e) {
e.printStackTrace();
return "0";
}
try {
if (dateFormat.parse(dateFormat.format(date)).after(defaultTime)) {
long diff = checkDate.getTime() - defaultTime.getTime();
Log.e("Difference", "onBindViewHolder: Difference: " + dateObj + " : " + defaultTime + " : " + diff);
if (diff > 0) {
long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000);
return "Late: " + diffHours + " Hour, " + diffMinutes + " Minutes, " + diffSeconds + " Sec";
} else {
return "0";
}
}
} catch (ParseException e) {
e.printStackTrace();
return "0";
}
return "0";
}

How to get Time Slot based on 1hour interval

I want to store time slot in the arraylist. i have start time and end time. based on start time it should create time slot.
For example if start time is 09:00AM and end time is 21:00PM then it should add into arraylist like below
09:00AM
10:00AM
11:00AM
12:00PM
13:00PM
14:00PM
..... so on
21:00PM
so one user books 13:00PM to 15:00PM slots so it should not be available to another user and other slot should be available. how to compare already booking time with new array list.
Code
private void getStartHourArray() {
times = new ArrayList<TimeSlot>();
Calendar calender = Calendar.getInstance();
calender.setTimeZone(TimeZone.getTimeZone("Asia/Calcutta"));
int ti = calender.get(Calendar.HOUR_OF_DAY);
int minutes = calender.get(Calendar.MINUTE);
System.out.println(minutes);
String[] quarterHours = {
"00",
"30",
};
boolean isflag = false;
times = new ArrayList<>();
for (int i = 9; i < 22; i++) {
if (ti > 8) {
for (int j = 0; j < 2; j++) {
if ((i == ti && minutes < Integer.parseInt(quarterHours[j])) || (i != ti) || isflag == true) {
isflag = true;
String time = i + ":" + quarterHours[j];
if (i < 10) {
time = "0" + time;
}
String hourFormat = i + ":" + quarterHours[j];
if (i < 12) {
hourFormat = time + " AM";
} else
hourFormat = time + " PM";
TimeSlot t = new TimeSlot();
t.time = hourFormat;
t.isAvailable = "Available";
times.add(t);
}
}
}
}
if (times != null) {
load.setVisibility(View.GONE);
}
}
Time Slot model class
public class TimeSlot {
public String time;
public String isAvailable;
}
Try something like this :
String firstDate = "26/02/2019";
String firstTime = "00:00 AM";
String secondDate = "26/02/2019";
String secondTime = "12:00 PM";
String format = "dd/MM/yyyy hh:mm a";
SimpleDateFormat sdf = new SimpleDateFormat(format);
Date dateObj1 = sdf.parse(firstDate + " " + firstTime);
Date dateObj2 = sdf.parse(secondDate + " " + secondTime);
System.out.println("Date Start: "+dateObj1);
System.out.println("Date End: "+dateObj2);
long dif = dateObj1.getTime();
while (dif < dateObj2.getTime()) {
Date slot = new Date(dif);
System.out.println("Hour Slot --->" + slot);
dif += 3600000;
}
This will give you a time slot for each hour, add this in ArrayList and when any user select time then remove that from ArrayList and update to the server so when next
user tries to get data it won't get the first selected user time slot.
try this:
import java.time.LocalTime;
import java.util.HashMap;
import java.util.Map;
public class PlayGround {
private Map<LocalTime, Boolean> slots = new HashMap();
public static void main(String[] args) {
PlayGround client = new PlayGround();
client.initializeSlots();
client.allocateSlots("10:00", "13:00");
//this shouldn't be available
client.allocateSlots("11:00", "12:00");
//not sure if u want this to be available. since it is start when the 1st just finished.
client.allocateSlots("13:00", "15:00");
client.allocateSlots("16:00", "18:00");
}
private void initializeSlots() {
LocalTime time = LocalTime.of(9, 0);
slots.put(time, true);
for (int i = 1; i < 24; i++) {
slots.put(time.plusHours(i), true);
}
}
private void allocateSlots(String strTime, String edTime) {
LocalTime startTime = LocalTime.parse(strTime);
LocalTime endTime = LocalTime.parse(edTime);
while (startTime.isBefore(endTime)) {
//check if the time slots between start and end time are available
if (!slots.get(startTime) || !slots.get(endTime)) {
System.out.println("slots not available" + " start time: " + strTime + " end time: " + edTime);
return;
}
startTime = startTime.plusHours(1);
endTime = endTime.minusHours(1);
}
System.out.println("slots are available" + " start time: " + strTime + " end time: " + edTime);
//then here u can mark all slots between to unavailable.
startTime = LocalTime.parse(strTime);
endTime = LocalTime.parse(edTime);
while (startTime.isBefore(endTime)) {
slots.put(startTime, false);
slots.put(endTime, false);
startTime = startTime.plusHours(1);
endTime = endTime.minusHours(1);
}
}
}

Android app not responding at Calender.getInstance

I am trying to get date doing calculations. For that I'm using Calendar cal = Calendar.getInstance();I am using this import import java.util.Calendar; When the app comes to onResume I am calling a method. In that method, the first line is getting Instance(). But for some reason, I am getting this error(ANR).
at java.util.Calendar.getInstance(Calendar.java:960)
at java.util.GregorianCalendar.<init>(GregorianCalendar.java:231)
at java.util.GregorianCalendar.<init>(GregorianCalendar.java:330)
at java.util.Calendar.<init>(Calendar.java:718)
at java.util.Calendar.<init>(Calendar.java:712)
Caused by: com.github.anrwatchdog.ANRError$$$_Thread: main
Caused by: com.github.anrwatchdog.ANRError: Application Not Responding
at com.github.anrwatchdog.ANRWatchDog.void run()(SourceFile:212)
at com.splunk.mint.Mint$3.void onAppNotResponding(com.github.anrwatchdog.ANRError)(SourceFile:297)
java.lang.Exception: com.github.anrwatchdog.ANRError: Application Not Responding
EDIT (adding code as asked)
public static int getCategory(final String time) {
long thenTime = SDKUtils.getLong(getLongValue(time));
Calendar c1 = Calendar.getInstance(); // today
Calendar c2 = Calendar.getInstance();
c2.setTime(new Date(thenTime)); // your date
if (c1.get(Calendar.YEAR) == c2.get(Calendar.YEAR) && c1.get(Calendar.DAY_OF_YEAR) == c2.get(Calendar.DAY_OF_YEAR))
return TODAY;
c1.add(Calendar.DAY_OF_YEAR, -1); // yesterday
if (c1.get(Calendar.YEAR) == c2.get(Calendar.YEAR) && c1.get(Calendar.DAY_OF_YEAR) == c2.get(Calendar.DAY_OF_YEAR))
return YESTERDAY;
c1 = Calendar.getInstance();
if (c1.get(Calendar.YEAR) == c2.get(Calendar.YEAR) )
return MONTH;
else
return YEAR;
}
public static String[] getSubTime(final String time, final int category) {
Calendar cal = Calendar.getInstance();
Date date = new Date(SDKUtils.getLong(getLongValue(time)));
TimeZone tz = TimeZone.getDefault();
cal.setTime(date);
cal.setTimeZone(tz);
int hour = cal.get(Calendar.HOUR_OF_DAY);
if (hour > 12)
hour = hour - 12;
int min = cal.get(Calendar.MINUTE);
String hourStr = hour < 10 ? "0" + hour : "" + hour;
String minStr = min < 10 ? "0" + min : "" + min;
String am = cal.get(Calendar.HOUR_OF_DAY) < 12 ? " AM" : " PM";
switch (category) {
case TODAY:
case YESTERDAY: {
return new String[] { hourStr + ":" + minStr + "", am };
}
case MONTH: {
int date_ = cal.get(Calendar.DAY_OF_MONTH);
String dateString = date_ < 10 ? "0" + date_ : date_ + "";
return new String[] { dateString, hourStr + ":" + minStr + "" + am };
}
case DATE: {
int date_ = cal.get(Calendar.DAY_OF_MONTH);
String dateString = date_ < 10 ? "0" + date_ : date_ + "";
return new String[] { dateString, hourStr + ":" + minStr + "" + am };
}
default: {
String month = convertNumberToMonthMMM(cal.get(Calendar.MONTH));
int date_ = cal.get(Calendar.DAY_OF_MONTH);
String dateString = date_ < 10 ? "0" + date_ : date_ + "";
return new String[] { month + " " + dateString, ", " + hourStr + ":" + minStr + "" + am };
}
}
}
These are the two methods i call. what is wrong?
Why you not try:
public class MainActivity extends AppCompatActivity
{
Calendar c = Calendar.getInstance();
#Override
protected void onCreate(Bundle savedInstanceState) {
}
}
Edit:
I think you're using:
import java.util.GregorianCalendar;
You try (add or) instead of:
import java.util.Calendar;
Regards

Java DateComparison

I use the code below to see if my input date (format mm/dd/yyyy HH:mm:ss) falls within the range of startDate and endDate.
I use compareTo() in this logic. But with the format mm/dd/yyyy, it compares the month alone and prints output in "MYLOGIC methood". But I need the year to be compared to see if the input date is within startDate and endDate range.
public class DateLogicNew {
public static void main(String[] args) {
String startDate[] = new String[1];
String endDate[] = new String[1];
startDate[0] = "01/01/0600 00:00:00";
endDate[0] = "11/27/3337 00:00:00";
String inputArr[] = { "05/01/0500 01:00:00", "11/27/3337 00:00:00",
"05/05/0700 00:00:00", "11/27/2337 00:00:00",
"06/05/4000 00:00:00" };
String protectedArr[] = new String[inputArr.length];
int temp[] = new int[inputArr.length];
System.out.println(inputArr.length);
System.out.println("Length of the inputArr: " + inputArr.length);
// System.out.println("");
for (int i = 0; i < inputArr.length; i++) {
if (inputArr[i]
.matches("^([0-1][0-9])/([0-3][0-9])/([0-9]{4})(?:( [0-2][0-9]):([0-5][0-9]):([0-5][0-9]))?$")) {
System.out.println("Inside if loop");
if (inputArr[i].compareTo(startDate[0]) > 0
&& inputArr[i].compareTo(endDate[0]) < 0) {
System.out.println("inside the compare condition");
temp[i] = 1;
protectedArr[i] = inputArr[i];
System.out
.println("Values of the inputArr in MYLOGIC method : "
+ protectedArr[i]);
}
} else {
temp[i] = 0;
}
}
System.out.println("");
for (int i = 0; i < inputArr.length; i++) {
if (temp[i] == 1) {
inputArr[i] = protectedArr[i];
}
System.out
.println("Final Value to the output port: " + inputArr[i]);
}
}
}
java.time
Parse as date-time objects. Regex is overkill.
The modern approach uses the java.time classes rather than the old legacy date-time classes.
String input = "05/01/0500 01:00:00" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM/dd/uuuu HH:mm:ss" ) ;
LocalDateTime ldt = LocalDateTime.parse( input , f ) ;
Compare using methods isBefore, isAfter, isEqual.
if( ( ! x.isBefore( start ) ) && x.isBefore( stop ) ) { … }
I myself figured out the solution for my question. Please check the code below to see the logic before comparing the dates.
String startDate = "0600/01/01 00:00:00";
String endDate = "3337/11/27 00:00:00";
try {
for (int i = 0; i < inputArr.length; i++) {
String newDateInput = inputArr[i];
// System.out.println("NewInput:" + newInput);
DateFormat parser = new SimpleDateFormat("MM/dd/yyyy");
DateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
Date convertedDate = parser.parse(newDateInput);
String newFormattedInput = formatter.format(convertedDate);
// System.out.println("newFormattedInput: " +
// newFormattedInput);
if (newFormattedInput
.matches("^([0-9]{4})/([0-1][0-9])/([0-3][0-9])(?:( [0-2][0-9]):([0-5][0-9]):([0-5][0-9]))?$")) {
if (newFormattedInput.compareTo(startDate) > 0
&& newFormattedInput.compareTo(endDate) < 0) {
temp[i] = 1;
protectedArr[i] = inputArr[i];
System.out
.println("Values of the inputArr in PROTECT method : "
+ protectedArr[i]);
} else {
temp[i] = 0;
}
}
}
} catch (ParseException e) {
e.printStackTrace();
}

Calculate number of weekend days records in array

I have a String Array which is contain dates that read from a CSV file.
Now I want to count how many weekend days are in that array. But in my array there are some dates are duplicated. Here shows part of the data that is containing in my Array.
12/2/2010
12/3/2010
12/5/2010
12/10/2010
12/5/2010
12/13/2010
12/14/2010
12/12/2010
In this data set 12/5/2010 is Sunday (but there are two records) & 12/12/2010 is Saturday (has One record). In output, I want to print number of weekend days in this array using java. Compared to this example the Answer should be 2.
FileInputStream fis=new FileInputStream("c:/cdr2.csv");
InputStreamReader isr=new InputStreamReader(fis);
BufferedReader bf = new BufferedReader(isr);
while (bf.ready()) {
String line = bf.readLine();
String[] values=line.split(",");
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/d/yyyy");
Date date = simpleDateFormat.parse(values[2]);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
}
First, you need to write a method that determines if a given Date is a weekend or not:
public static boolean isWeekend(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
return dayOfWeek == Calendar.SUNDAY || dayOfWeek == Calendar.SATURDAY;
}
Then, you need to define a DateFormat, so that you can parse a date String into a java.util.Date. Finally, you can use a Set to assure every weekend you find is not going to be duplicated:
public static void main(String[] args) throws ParseException {
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
String[] dates = { "12/2/2010", "12/3/2010", "12/5/2010", "12/10/2010", "12/5/2010", "12/13/2010", "12/14/2010", "12/12/2010" };
Set<String> weekends = new HashSet<String>();
for (String dt : dates) {
Date date = dateFormat.parse(dt);
if (isWeekend(date)) {
weekends.add(dt);
}
}
System.out.println("There are " + weekends.size() + " distinct weekends."); // 2
}
I would say you need to first remove duplicates and then check which of them are weekend days:
Set<String> set = new HashSet<String>( Arrays.asList(yourArrayOfDateStrings) );
DateFormat df = new SimpleDateFormat(yourDatePattern);
Calendar calendar = Calendar.getInstance();
int weekendDays = 0;
for (String dateString : set) {
calendar.setTime( df.parse(dateString) );
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
if (dayOfWeek == Calendar.SATURDAY || dayOfWeek == Calendar.SUNDAY) {
weekendDays++;
}
}
I don't use java date, ever!
I agree with Costi Ciudatu, use a Set to remove duplicates.
:) please to send you teh codez using JodaTime
import org.joda.time.DateTime;
import org.joda.time.DateTimeConstants;
import org.joda.time.DateTimeField;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.Set;
public class Dates
{
static String[] localTestDate = new String[] {"12/2/2010", "12/3/2010", "12/5/2010", "12/10/2010", "12/5/2010", "12/13/2010", "12/14/2010", "12/12/2010"};
static DateTimeFormatter dateFactory = DateTimeFormat.forPattern("MM/d/yyyy");
public static void main(String[] args)
{
// final Set<DateTime> uniqueDates = generateUniqueDates(localTestDate);
final Set<DateTime> uniqueDates = generateUniqueDates(readCommonSeparatedFile(args[0]));
int numberOfWeekendDates = 0;
for(DateTime date : uniqueDates)
{
if(isWeekend(date)) numberOfWeekendDates++;
}
System.out.println("There are " + numberOfWeekendDates + " weekend days in your list.");
}
private static boolean isWeekend(DateTime dateTime)
{
return (DateTimeConstants.SATURDAY == dateTime.dayOfWeek().get() || DateTimeConstants.SUNDAY == dateTime.dayOfWeek().get());
}
private static String[] readCommonSeparatedFile(final String fileName)
{
FileInputStream fileInputStream = null;
String[] result = null;
try
{
fileInputStream = new FileInputStream(fileName);
final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream));
while (bufferedReader.ready())
{
String line = bufferedReader.readLine();
result = line.split(",");
}
}
catch (IOException e)
{
//log error some where
throw new RuntimeException("aw, snap!");
}
return result;
}
private static Set<DateTime> generateUniqueDates(final String[] dates)
{
final Set<DateTime> dateTimes = new HashSet<DateTime>();
for (String date : dates)
{
dateTimes.add(dateFactory.parseDateTime(date).toDateTime());
}
return dateTimes;
}
}

Categories

Resources