how to remove data from hashtable for a particular date - java

I am trying to remove data from hashtable for a particular date,the hashtable is of type (String,vector).Initially i am checking if hashtable contains the usrDate if yes then i need to remove all the data frm hashtable only for usrDate and add the new data that is listEvents.But the contains from hashtable for other dates should not be deleted.
listEvents.addElement(eventBean);//new data is here
for (int i = 0; i < listEvents.size();i++) {
EventData e = (EventData)listEvents.elementAt(i);
}
//checking if hashtable has given date
if (listUserEvents.containsKey(usrDate)) {
Vector info = (Vector)listUserEvents.get(usrDate);
info.addElement(eventBean);
listUserEvents.put(usrDate,info);
} else {
listUserEvents.put(usrDate,listEvents);
}
i just want to add listEvents to the hashtable for the given date,without affecting the other data in hashtable which has data for some other dates.
private Hashtable getEvents(String usrDate, String timezone) {
try {
listUserEvents = getUserInfo();
listEvents = new Vector();
Calendar calendarLocalEvent = Calendar.getInstance();
// fetches time zone
TimeZone timeZoneEvent = calendarLocalEvent.getTimeZone();
System.out.println("Time Zone first-->"
+ timeZoneEvent.getDefault());
if (timezone.equals(timeZoneEvent.getDefault())) {
;
} else {
TimeZone timeZoneChange = TimeZone.getTimeZone(timezone);
System.out.println("Time Zone change-->" +timeZoneChange);
Device.setTimeZone(timeZoneChange);
}
EventList eventList = (EventList) PIM.getInstance().openPIMList(
PIM.EVENT_LIST, PIM.READ_ONLY);
Enumeration events = eventList.items();
while (events.hasMoreElements()) {
System.out.println("in while");
Event event = (Event) events.nextElement();
if (eventList.isSupportedField(Event.START)
&& event.countValues(Event.START) > 0)
{
long start = event.getDate(Event.START, 0);
SimpleDateFormat sdf = new SimpleDateFormat(
"MMM dd,yyyy HH:mm");
SimpleDateFormat sdf_start = new SimpleDateFormat("HH:mm");
SimpleDateFormat sdf_start_min = new SimpleDateFormat("HH");
String dateString = sdf.formatLocal(start);
String timeString = sdf_start.formatLocal(start);
String hour = sdf_start_min.formatLocal(start);
SimpleDateFormat sdf1 = new SimpleDateFormat("MMM dd,yyyy");
String date = sdf1.formatLocal(start);
System.out.println("dates are :" + date +"user" + usrDate);
if (usrDate.equalsIgnoreCase(date)) {
System.out.println("dates are equal:" +date);
EventData eventBean = new EventData();
if (eventList.isSupportedField(Event.END)
&& event.countValues(Event.END) > 0) {
long end = event.getDate(Event.END, 0);
SimpleDateFormat sdform = new SimpleDateFormat(
"MMM dd, yyyy HH:mm");
SimpleDateFormat sdfTime = new SimpleDateFormat(
"HH:mm");
SimpleDateFormat sdfhr = new SimpleDateFormat("HH");
String dateString1 =sdform.formatLocal(end);
String timeString1 =sdfTime.formatLocal(end);
String hr = sdfhr.formatLocal(end);
eventBean.setStartHr(hour);
eventBean.setEndHr(hr);
eventBean.setStartTime(timeString);
eventBean.setEndTime(timeString1);
eventBean.setStartDate(dateString);
eventBean.setEndDate(dateString1);
// Dialog.alert("equal startdate" + dateString);
// Dialog.alert("equal end date"+ dateString1);
}
if (eventList.isSupportedField(Event.LOCATION)
&& event.countValues(Event.LOCATION) > 0) {
String location = event
.getString(Event.LOCATION, 0);
eventBean.setLocation(location);
// Dialog.alert("equal location"+ location);
}
if (eventList.isSupportedField(Event.SUMMARY)
&& event.countValues(Event.SUMMARY) > 0) {
String subject = event.getString(Event.SUMMARY, 0);
eventBean.setSummary(subject);
// Dialog.alert("equal subject" +subject);
}
eventBean.setUserDate(usrDate);
eventBean.setTimeZone(timezone);
listEvents.addElement(eventBean);
System.out.println("the size bf hashis"
+ listEvents.size());
for (int i = 0; i < listEvents.size();i++) {
EventData e = (EventData)listEvents.elementAt(i);
System.out.println("so thesummary is ::"
+ e.getSummary());
}
// for(int i=0;i<listUserEvents.size();i++){
if (listUserEvents.containsKey(usrDate)) {
// listUserEvents.remove(usrDate);
Vector info = (Vector)listUserEvents.get(usrDate);
System.out.println("the size in getEvents is"
+ info.size());
if(info.contains(usrDate)){
System.out.println("in info");
}
info.addElement(eventBean);
System.out.println("vector size info is"
+ info.size());
listUserEvents.put(usrDate,info);
} else {
System.out.println("in else of getevent" +listEvents.size());
listUserEvents.put(usrDate,listEvents);
}
// }
} else {
// Dialog.alert("not equal");
}
}
}
Device.setTimeZone(timeZoneEvent);
Calendar calendarLocalLastEvent = Calendar.getInstance();
// fetches time zone
TimeZone timeZoneEventLast =calendarLocalLastEvent.getTimeZone();
System.out.println("Time Zone last-->"
+ timeZoneEventLast.getDefault());
} catch (PIMException e) {
// //Dialog.alert(e.getMessage());
}
System.out.println("size in hashtable " + listUserEvents.size());
return listUserEvents;
}

It must be something like this
for(int i = 0; i<listUserEvents.size();i++)
{
if (listUserEvents.containsKey(usrDate)){
listUserEvents.remove(usrDate);
}
}

Here is a simple example of how this works:
Hashtable<String, Integer> numbers = new Hashtable<String, Integer>();
numbers.put("one", 1);
numbers.put("two", 2);
if (numbers.containsKey("two")) {
numbers.put("two", 222);
}
What are you having difficulty at? Moreover what is the type of your Hashtable key? Is it java.util.Date or something else?

Related

what method can i use to change format 12 hours time to 24 hour time [duplicate]

In my app, I have a requirement to format 12 hours time to 24 hours time. What is the method I have to use?
For example, time like 10:30 AM. How can I convert to 24 hours time in java?
Try this:
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
public static void main(String [] args) throws Exception {
SimpleDateFormat displayFormat = new SimpleDateFormat("HH:mm");
SimpleDateFormat parseFormat = new SimpleDateFormat("hh:mm a");
Date date = parseFormat.parse("10:30 PM");
System.out.println(parseFormat.format(date) + " = " + displayFormat.format(date));
}
}
which produces:
10:30 PM = 22:30
See: http://download.oracle.com/javase/1.5.0/docs/api/java/text/SimpleDateFormat.html
java.time
In Java 8 and later it could be done in one line using class java.time.LocalTime.
In the formatting pattern, lowercase hh means 12-hour clock while uppercase HH means 24-hour clock.
Code example:
String result = // Text representing the value of our date-time object.
LocalTime.parse( // Class representing a time-of-day value without a date and without a time zone.
"03:30 PM" , // Your `String` input text.
DateTimeFormatter.ofPattern( // Define a formatting pattern to match your input text.
"hh:mm a" ,
Locale.US // `Locale` determines the human language and cultural norms used in localization. Needed here to translate the `AM` & `PM` value.
) // Returns a `DateTimeFormatter` object.
) // Return a `LocalTime` object.
.format( DateTimeFormatter.ofPattern("HH:mm") ) // Generate text in a specific format. Returns a `String` object.
;
See this code run live at IdeOne.com.
15:30
See Oracle Tutorial.
Assuming that you use SimpleDateFormat implicitly or explicitly, you need to use H instead of h in the format string.
E.g
HH:mm:ss
instead of
hh:mm:ss
12 to 24 hour time conversion and can be reversed if change time formate in output and input SimpleDateFormat class parameter
Test Data Input:
String input = "07:05:45PM";
timeCoversion12to24(input);
output
19:05:45
public static String timeCoversion12to24(String twelveHoursTime) throws ParseException {
//Date/time pattern of input date (12 Hours format - hh used for 12 hours)
DateFormat df = new SimpleDateFormat("hh:mm:ssaa");
//Date/time pattern of desired output date (24 Hours format HH - Used for 24 hours)
DateFormat outputformat = new SimpleDateFormat("HH:mm:ss");
Date date = null;
String output = null;
//Returns Date object
date = df.parse(twelveHoursTime);
//old date format to new date format
output = outputformat.format(date);
System.out.println(output);
return output;
}
SimpleDateFormat parseFormat = new SimpleDateFormat("hh:mm a");
provided by Bart Kiers answer should be replaced with somethig like
SimpleDateFormat parseFormat = new SimpleDateFormat("hh:mm a",Locale.UK);
Try This
public static String convertTo24Hour(String Time) {
DateFormat f1 = new SimpleDateFormat("hh:mm a"); //11:00 pm
Date d = null;
try {
d = f1.parse(Time);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
DateFormat f2 = new SimpleDateFormat("HH:mm");
String x = f2.format(d); // "23:00"
return x;
}
static String timeConversion(String s)
{
String s1[]=s.split(":");
char c[]=s1[2].toCharArray();
if(s1[2].contains("PM"))
{
int n=Integer.parseInt(s1[0]);
n=n+12;
return n+":"+s1[1]+":"+c[0]+c[1];
}
else``
return s1[0]+":"+s1[1]+":"+c[0]+c[1];
}
It can be done using Java8 LocalTime. Here is the code.
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
public class TimeConversion {
public String timeConversion(String s) {
LocalTime.parse(s, DateTimeFormatter.ofPattern("hh:mm a"));
}
}
And Here is the test case for the same:
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class TimeConversionTest {
#Test
void shouldReturnTimeIn24HrFormat() {
TimeConversion timeConversion = new TimeConversion();
Assertions.assertEquals("22:30", timeConversion.timeConversion("10:30 PM"));
}
}
Using LocalTime in Java 8, LocalTime has many useful methods like getHour() or the getMinute() method,
For example,
LocalTime intime = LocalTime.parse(inputString, DateTimeFormatter.ofPattern("h:m a"));
String outtime = intime.format(DateTimeFormatter.ISO_LOCAL_TIME);
In some cases, First line alone can do the required parsing
This is the extract of code that I have done.
String s="08:10:45";
String[] s1=s.split(":");
int milipmHrs=0;
char[] arr=s1[2].toCharArray();
boolean isFound=s1[2].contains("PM");
if(isFound){
int pmHrs=Integer.parseInt(s1[0]);
milipmHrs=pmHrs+12;
return(milipmHrs+":"+s1[1]+":"+arr[0]+arr[1]);
}
else{
return(s1[0]+":"+s1[1]+":"+arr[0]+arr[1]);
}
import java.text.SimpleDateFormat;
import java.text.DateFormat;
import java.util.Date;
public class Main {
public static void main(String [] args){
try {
DateFormat parseFormat = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss a");
String sDate = "22-01-2019 9:0:0 PM";
Date date = parseFormat.parse(sDate);
SimpleDateFormat displayFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
sDate = displayFormat.format(date);
LOGGER.info("The required format : " + sDate);
} catch (Exception e) {}
}
}
Try this to calculate time difference between two times.
first it will convert 12 hours time into 24 hours then it will take diff between two times
String a = "09/06/18 01:55:33 AM";
String b = "07/06/18 05:45:33 PM";
String [] b2 = b.split(" ");
String [] a2 = a.split(" ");
SimpleDateFormat displayFormat = new SimpleDateFormat("HH:mm:ss");
SimpleDateFormat parseFormat = new SimpleDateFormat("hh:mm:ss a");
String time1 = null ;
String time2 = null ;
if ( a.contains("PM") && b.contains("AM")) {
Date date = parseFormat.parse(a2[1]+" PM");
time1 = displayFormat.format(date);
time2 = b2[1];
}else if (b.contains("PM") && a.contains("AM")) {
Date date = parseFormat.parse(a2[1]+" PM");
time1 = a2[1];
time2 = displayFormat.format(date);
}else if (a.contains("PM") && b.contains("PM")){
Date datea = parseFormat.parse(a2[1]+" PM");
Date dateb = parseFormat.parse(b2[1]+" PM");
time1 = displayFormat.format(datea);
time2 = displayFormat.format(dateb);
}
System.out.println(time1);
System.out.println(time2);
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
Date date1 = format.parse(time1);
Date date2 = format.parse(time2);
long difference = date2.getTime() - date1.getTime();
System.out.println(difference);
System.out.println("Duration: "+DurationFormatUtils.formatDuration(difference, "HH:mm"));
For More Details Click Here
I have written a simple utility function.
public static String convert24HourTimeTo12Hour(String timeStr) {
try {
DateFormat inFormat = new SimpleDateFormat( "HH:mm:ss");
DateFormat outFormat = new SimpleDateFormat( "hh:mm a");
Date date = inFormat.parse(timeStr);
return outFormat.format(date);
}catch (Exception e){}
return "";
}
Try this below code,
public static String timeConversion(String s) {
String militaryTime = "";
String hourString = s.substring(0,2);
String timeFormat = s.substring(8,10);
String timeBody = s.substring(2,8);
if (timeFormat.equals("AM")){
if (hourString.equals("12")){
militaryTime = "00" + timeBody;
}else{
militaryTime = hourString + timeBody;
}
}else if (timeFormat.equals("PM")){
if (hourString.equals("12")){
militaryTime = hourString + timeBody;
}else{
int value = Integer.parseInt(hourString) + 12;
militaryTime = String.valueOf(value) + timeBody;
}
}
return militaryTime;
}
Without using library methods
public static String timeConversion(String s) {
String[] timeElements = s.split(":");
if (s.contains("PM")) {
timeElements[0] = getPMHours(timeElements[0]);
} else {
timeElements[0] = getAMHours(timeElements[0]);
}
timeElements[2] = timeElements[2].substring(0,2);
return timeElements[0]+":"+timeElements[1]+":"+timeElements[2];
}
private static String getAMHours(String hour) {
if(Integer.parseInt(hour) == 12) return "00";
return hour;
}
private static String getPMHours(String hour) {
int i = Integer.parseInt(hour);
if(i != 12) return 12+i+"";
return i+"";
}
I was looking for same thing but in number, means from integer xx hour, xx minutes and AM/PM to 24 hour format xx hour and xx minutes, so here what i have done:
private static final int AM = 0;
private static final int PM = 1;
/**
* Based on concept: day start from 00:00AM and ends at 11:59PM,
* afternoon 12 is 12PM, 12:xxAM is basically 00:xxAM
* #param hour12Format
* #param amPm
* #return
*/
private int get24FormatHour(int hour12Format,int amPm){
if(hour12Format==12 && amPm==AM){
hour12Format=0;
}
if(amPm == PM && hour12Format!=12){
hour12Format+=12;
}
return hour12Format;
}`
private int minutesTillMidnight(int hour12Format,int minutes, int amPm){
int hour24Format=get24FormatHour(hour12Format,amPm);
System.out.println("24 Format :"+hour24Format+":"+minutes);
return (hour24Format*60)+minutes;
}
We can solve this by using String Buffer
String s;
static String timeConversion(String s) {
StringBuffer st=new StringBuffer(s);
for(int i=0;i<=st.length();i++){
if(st.charAt(0)=='0' && st.charAt(1)=='1' &&st.charAt(8)=='P' ){
// if(st.charAt(2)=='1'){
// st.replace(1,2,"13");
st.setCharAt(0, '1');
st.setCharAt(1, '3');
}else if(st.charAt(0)=='0' && st.charAt(1)=='2' &&st.charAt(8)=='P' ){
// if(st.charAt(2)=='1'){
// st.replace(1,2,"13");
st.setCharAt(0, '1');
st.setCharAt(1, '4');
}else if(st.charAt(0)=='0' && st.charAt(1)=='3' &&st.charAt(8)=='P' ){
// if(st.charAt(2)=='1'){
// st.replace(1,2,"13");
st.setCharAt(0, '1');
st.setCharAt(1, '5');
}else if(st.charAt(0)=='0' && st.charAt(1)=='4' &&st.charAt(8)=='P' ){
// if(st.charAt(2)=='1'){
// st.replace(1,2,"13");
st.setCharAt(0, '1');
st.setCharAt(1, '6');
}else if(st.charAt(0)=='0' && st.charAt(1)=='5' &&st.charAt(8)=='P' ){
// if(st.charAt(2)=='1'){
// st.replace(1,2,"13");
st.setCharAt(0, '1');
st.setCharAt(1, '7');
}else if(st.charAt(0)=='0' && st.charAt(1)=='6' &&st.charAt(8)=='P' ){
// if(st.charAt(2)=='1'){
// st.replace(1,2,"13");
st.setCharAt(0, '1');
st.setCharAt(1, '8');
}else if(st.charAt(0)=='0' && st.charAt(1)=='7' &&st.charAt(8)=='P' ){
// if(st.charAt(2)=='1'){
// st.replace(1,2,"13");
st.setCharAt(0, '1');
st.setCharAt(1, '9');
}else if(st.charAt(0)=='0' && st.charAt(1)=='8' &&st.charAt(8)=='P' ){
// if(st.charAt(2)=='1'){
// st.replace(1,2,"13");
st.setCharAt(0, '2');
st.setCharAt(1, '0');
}else if(st.charAt(0)=='0' && st.charAt(1)=='9' &&st.charAt(8)=='P' ){
// if(st.charAt(2)=='1'){
// st.replace(1,2,"13");
st.setCharAt(0, '2');
st.setCharAt(1, '1');
}else if(st.charAt(0)=='1' && st.charAt(1)=='0' &&st.charAt(8)=='P' ){
// if(st.charAt(2)=='1'){
// st.replace(1,2,"13");
st.setCharAt(0, '2');
st.setCharAt(1, '2');
}else if(st.charAt(0)=='1' && st.charAt(1)=='1' &&st.charAt(8)=='P' ){
// if(st.charAt(2)=='1'){
// st.replace(1,2,"13");
st.setCharAt(0, '2');
st.setCharAt(1, '3');
}else if(st.charAt(0)=='1' && st.charAt(1)=='2' &&st.charAt(8)=='A' ){
// if(st.charAt(2)=='1'){
// st.replace(1,2,"13");
st.setCharAt(0, '0');
st.setCharAt(1, '0');
}else if(st.charAt(0)=='1' && st.charAt(1)=='2' &&st.charAt(8)=='P' ){
st.setCharAt(0, '1');
st.setCharAt(1, '2');
}
if(st.charAt(8)=='P'){
st.setCharAt(8,' ');
}else if(st.charAt(8)== 'A'){
st.setCharAt(8,' ');
}
if(st.charAt(9)=='M'){
st.setCharAt(9,' ');
}
}
String result=st.toString();
return result;
}

Java Format Timestamp

I have below Java code to convert string format to Timestamp object
public class TestUtil{
Object result;
Public Object convertFormat(String format, String value, String type){
String format = "yyyyMMddHHmmss";
String value = "20050225144824";
SimpleDateFormat dformat = new SimpleDateFormat(format);
java.util.Date date = dformat.parse(value);
result = new Timestamp(date.getTime);
System.out.println("Result::"+ result);
}
}
Expected outcome:
I was expecting the outcome should be like below
20050225144824
Actual outcome:
2005-02-25 14:48:24.0
Could anyone tell me what I am missing here? To get "20050225144824" this result
The below code runs fine for me.
Adding few print statements to explain the different behaviors.
import java.util.Date;
import java.text.SimpleDateFormat;
import java.sql.Timestamp;
public class Main
{
public static void main(String[] args) {
String myFormat = "yyyyMMddHHmmss";
String value = "20050225144824";
try {
SimpleDateFormat dformat = new SimpleDateFormat("yyyyMMddHHmmss");
Date date = dformat.parse(value);
Timestamp ts = new Timestamp(date.getTime());
Object result = new Timestamp(date.getTime());
System.out.println("Timestamp Format with yyyyMMddHHmmss : " +dformat.format(ts));
System.out.println("Object Format with yyyyMMddHHmmss : " +result);
System.out.println("Object Format with yyyyMMddHHmmss : " +dformat.format(result));
} catch(Exception e) {
e.printStackTrace();
}
}
}
Here is the output of the different behaviors :
Timestamp Format with yyyyMMddHHmmss : 20050225144824
Object Format with yyyyMMddHHmmss : 2005-02-25 14:48:24.0
Object Format with yyyyMMddHHmmss : 20050225144824
If you expect Timestamp to return your custom output then you need to override the default Timestamp library.
Here I create CustomTimestamp.java to extend Timestamp and override its toString() method. I modified the changes according to your requirement.
public class CustomTimestamp extends Timestamp {
private int nanos;
public CustomTimestamp(long time) {
super(time);
}
#Override
public String toString () {
int year = super.getYear() + 1900;
int month = super.getMonth() + 1;
int day = super.getDate();
int hour = super.getHours();
int minute = super.getMinutes();
int second = super.getSeconds();
String yearString;
String monthString;
String dayString;
String hourString;
String minuteString;
String secondString;
String nanosString;
String zeros = "000000000";
String yearZeros = "0000";
StringBuffer timestampBuf;
if (year < 1000) {
// Add leading zeros
yearString = "" + year;
yearString = yearZeros.substring(0, (4-yearString.length())) +
yearString;
} else {
yearString = "" + year;
}
if (month < 10) {
monthString = "0" + month;
} else {
monthString = Integer.toString(month);
}
if (day < 10) {
dayString = "0" + day;
} else {
dayString = Integer.toString(day);
}
if (hour < 10) {
hourString = "0" + hour;
} else {
hourString = Integer.toString(hour);
}
if (minute < 10) {
minuteString = "0" + minute;
} else {
minuteString = Integer.toString(minute);
}
if (second < 10) {
secondString = "0" + second;
} else {
secondString = Integer.toString(second);
}
if (nanos == 0) {
nanosString = "";
} else {
nanosString = Integer.toString(nanos);
// Add leading zeros
nanosString = zeros.substring(0, (9-nanosString.length())) +
nanosString;
// Truncate trailing zeros
char[] nanosChar = new char[nanosString.length()];
nanosString.getChars(0, nanosString.length(), nanosChar, 0);
int truncIndex = 8;
while (nanosChar[truncIndex] == '0') {
truncIndex--;
}
nanosString = new String(nanosChar, 0, truncIndex + 1);
}
// do a string buffer here instead.
timestampBuf = new StringBuffer(20+nanosString.length());
timestampBuf.append(yearString);
timestampBuf.append(monthString);
timestampBuf.append(dayString);
timestampBuf.append(hourString);
timestampBuf.append(minuteString);
timestampBuf.append(secondString);
timestampBuf.append(nanosString);
return (timestampBuf.toString());
}
}
Your main class should use CustomTimestamp to get the output
try {
String format = "yyyyMMddHHmmss";
String value = "20050225144824";
SimpleDateFormat dformat = new SimpleDateFormat(format);
java.util.Date date;
date = dformat.parse(value);
Timestamp result = new CustomTimestamp(date.getTime());
System.out.println("Result::" + result);
} catch (ParseException e) {
e.printStackTrace();
}

How to get all events from SQlite database in Alamkanak Android-Week-View library ? (i keep getting single Event)?

I am trying to add events dynamically from the my SQLite database , but i get a single event in my Week-view which it is the last event i add in the database , i am using Alamkanak Week-View , i stuck with problem and try many ways , please help guys .
mWeekView.setMonthChangeListener(new MonthLoader.MonthChangeListener() {
#Override
public List<? extends WeekViewEvent> onMonthChange(int newYear, int newMonth) {
ArrayList<WeekViewEvent> lastevents = new ArrayList<WeekViewEvent>();
lastevents = loadDateFromJson(newYear,newMonth);
events.addAll(loadDateFromJson(newYear,newMonth));
return events;
}
} );
}
public ArrayList<WeekViewEvent> getmNewEvents(int year , int month ) {
// Parse time.
SimpleDateFormat sdf = new SimpleDateFormat("HH:MM");
Date start = new Date();
Date end = new Date();
start = getMyTime();
try {
end = sdf.parse(new Event().getEndTime());
} catch (ParseException e) {
e.printStackTrace();
}
Calendar now = Calendar.getInstance();
Calendar startTime = (Calendar) now.clone();
startTime.setTimeInMillis(start.getTime());
startTime.set(Calendar.YEAR, now.get(Calendar.YEAR));
startTime.set(Calendar.MONTH, now.get(Calendar.MONTH));
startTime.set(Calendar.DAY_OF_MONTH, getMyDate());
Calendar endTime = (Calendar) startTime.clone();
endTime.add(Calendar.HOUR_OF_DAY, 3);
// Create an week view event.
ArrayList<WeekViewEvent> ThisMonthsEvents = new ArrayList<WeekViewEvent>();
WeekViewEvent weekViewEvent =new WeekViewEvent(1,"Raouf",startTime,endTime);
mNewEvents.add(weekViewEvent);
for (int i = 0; i < mNewEvents.size(); i++) {
mNewEvents.get(i).getStartTime().get(Calendar.MONTH);
if((mNewEvents.get(i).getStartTime().get(Calendar.MONTH) == month)&&(mNewEvents.get(i).getStartTime().get(Calendar.YEAR) == year))
ThisMonthsEvents.add(mNewEvents.get(i));
}
ArrayList<WeekViewEvent> matchedEvents = new ArrayList<WeekViewEvent>();
for (WeekViewEvent event : mNewEvents) {
if (eventMatches(event, year, month)) {
matchedEvents.add(event);
}
}
mWeekView.notifyDatasetChanged();
return ThisMonthsEvents;
}
// here how i am getting dates from my SQlite Database
public int getMyDate() {
DBconexion db = new DBconexion(this);
SQLiteDatabase db2 = db.getReadableDatabase();
Cursor cur = db2.rawQuery("SELECT * FROM " + Table_name, null);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-mm-yyyy");
// looping through all rows and adding to list
String date = null;
Date Date = new Date();
ArrayList<String> dateStringList = new ArrayList<String>();
ArrayList<Date> dateList = new ArrayList<Date>();
int DayOfMonth = 0;
while (cur.moveToNext()) {
dateStringList.add(cur.getString(9));
}
for (String dateString : dateStringList) {
try {
dateList.add(simpleDateFormat.parse(dateString));
} catch (ParseException e) {
e.printStackTrace();
}
}
for (Date datee : dateList) {
DayOfMonth = datee.getDate();
}
return DayOfMonth;
}
i find how to solve this , i use JSONArrays and it works perfectly
here is the code maybe someone will need it!
public List<WeekViewEvent> loadDateFromJson(int year , int month) {
DBconexion dBconexion = new DBconexion(this);
#SuppressLint("SimpleDateFormat") SimpleDateFormat sdfD = new SimpleDateFormat("yy-MM-dd");
#SuppressLint("SimpleDateFormat") SimpleDateFormat sdfT = new SimpleDateFormat("HH:mm");
try {
JSONObject jo = dBconexion.getDateTime();
JSONArray Datejason = jo.getJSONArray("Date");
JSONArray Timejason = jo.getJSONArray("Time");
JSONArray endTimejason = jo.getJSONArray("End Time");
JSONArray Namejason = jo.getJSONArray("Name");
for (int i = 0; i < Datejason.length(); i++) {
//set date
String sd = (String) Datejason.get(i);
Date dfj = sdfD.parse(sd);
int Day = dfj.getDate();
int Month = dfj.getMonth() - 0;
int Year = dfj.getYear();
//set time
String st = (String) Timejason.get(i);
Date tfj = sdfT.parse(st);
int Hour = tfj.getHours();
int Minute = tfj.getMinutes();
String endTimeP = (String) endTimejason.getString(i);
int endTimePeriod = Integer.valueOf(endTimeP);
//set name
String Name = (String) Namejason.getString(i);
//Rand Colors for Events
Random rand = new Random();
int r = rand.nextInt(255);
int g = rand.nextInt(255);
int b = rand.nextInt(255);
int randomColor = Color.rgb(r,g,b);
if(Color.rgb(r,g,b) == getResources().getColor(R.color.white)){
randomColor = getResources().getColor(R.color.red);
}
//Set StarTime
Calendar startTime = Calendar.getInstance();
startTime.set(Calendar.HOUR_OF_DAY, Hour);
startTime.set(Calendar.MINUTE, Minute);
startTime.set(Calendar.YEAR, year);
startTime.set(Calendar.MONTH, Month);
startTime.set(Calendar.DAY_OF_MONTH, Day);
Calendar endTime = (Calendar) startTime.clone();
endTime.add(Calendar.HOUR_OF_DAY, endTimePeriod);
WeekViewEvent weekViewEvent = new WeekViewEvent(1, Name, startTime, endTime);
weekViewEvent.setColor(randomColor);
myEvent.add(weekViewEvent);
}
} catch (JSONException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
return myEvent;
}
onMonthChange will look like
mWeekView.setMonthChangeListener(new MonthLoader.MonthChangeListener() {
#Override
public List<? extends WeekViewEvent> onMonthChange(int newYear, int newMonth) {
List<WeekViewEvent> lastone = new ArrayList<WeekViewEvent> ();
lastone = loadDateFromJson( newYear , newMonth);
events.addAll(lastone);
ArrayList<WeekViewEvent> matchedEvents = new ArrayList<WeekViewEvent>();
for (WeekViewEvent event : events) {
if (eventMatches(event, newYear, newMonth)) {
matchedEvents.add(event);
}
}
return matchedEvents;
}
} );
}

How to Compare datetime in Android

I have dates, date1(now) and date2 which is returned in a JSON string say 2016-07-09 21:26:04.
I want to compare those two dates something like
if(date1 < date2){
}
Here is the code to compare two DateTime objects in Android:
public void onDateSelected(DateTime dateSelected) {
DateTime currentDateTime = new DateTime();
try{
// You can use any format to compare by spliting the dateTime
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ");
String str1 = dateSelected.toString();
Date selectedDate = formatter.parse(str1);
String str2 = currentDateTime.toString();
Date currentDate = formatter.parse(str2);
if (selectedDate.compareTo(currentDate)<0)
{
System.out.println("current date is Greater than my selected date");
}
else
{
System.out.println("selected date is Greater than my current date");
}
}catch (ParseException e1){
e1.printStackTrace();
}
}
I would do this:
parse the in to Date objects
compare those
Example:
public static void main(String x[]) throws ParseException {
String s1 = "2016-07-09 21:26:04";
String s2 = "2006-07-09 21:26:04";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date d1 = sdf.parse(s1);
Date d2 = sdf.parse(s2);
int compareResult = d1.compareTo(d2);
if (compareResult > 0) {
System.out.println(s1 + " is younger than " + s2);
} else if (compareResult < 0) {
System.out.println(s1 + " is younger than " + s2);
} else {
System.out.println(s1 + " is equals than " + s2);
}
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date today= new Date();
try {
if (today.before(sdf.forrmat(json_string_date))) {
// If start date is before end date.
// Do your piece of code
}
}catch (ParseException e) {
e.printStackTrace();
}

Check if time is inbetween timerange in Android

I am trying to check if the current time is in the range of a specified range. I made a method to check this, but it doesn't work. I'm not sure why not and how to get it to work.
private Calendar fromTime;
private Calendar toTime;
private Calendar currentTime;
public boolean checkTime(String time) {
try {
String[] times = time.split("-");
String[] from = times[0].split(":");
String[] until = times[1].split(":");
fromTime = Calendar.getInstance();
fromTime.set(Calendar.HOUR, Integer.valueOf(from[0]));
fromTime.set(Calendar.MINUTE, Integer.valueOf(from[1]));
toTime= Calendar.getInstance();
toTime.set(Calendar.HOUR, Integer.valueOf(until[0]));
toTime.set(Calendar.MINUTE, Integer.valueOf(until[1]));
currentTime = Calendar.getInstance();
currentTime.set(Calendar.HOUR, Calendar.HOUR_OF_DAY);
currentTime.set(Calendar.MINUTE, Calendar.MINUTE);
if(currentTime.after(fromTime) && currentTime.before(toTime)){
return true;
}
} catch (Exception e) {
return false;
}
return false;
}
I am trying to test it like this:
if(checkTime("06:00-19:00")){
inRange = true;
}
The NPE is gone, but it's still not calculating if the time is in the range of fromTime to toTime. Any help is very much appreciated!
Initialize variables and change the return type of your method to boolean.
private Calendar fromTime;
private Calendar toTime;
private Calendar currentTime;
public boolean checkTime(String time) {
try {
String[] times = time.split("-");
String[] from = times[0].split(":");
String[] until = times[1].split(":");
fromTime = Calendar.getInstance();
fromTime.set(Calendar.HOUR_OF_DAY, Integer.valueOf(from[0]));
fromTime.set(Calendar.MINUTE, Integer.valueOf(from[1]));
toTime = Calendar.getInstance();
toTime.set(Calendar.HOUR_OF_DAY, Integer.valueOf(until[0]));
toTime.set(Calendar.MINUTE, Integer.valueOf(until[1]));
currentTime = Calendar.getInstance();
currentTime.set(Calendar.HOUR_OF_DAY, Calendar.HOUR_OF_DAY);
currentTime.set(Calendar.MINUTE, Calendar.MINUTE);
if(currentTime.after(fromTime) && currentTime.before(toTime)){
return true;
}
} catch (Exception e) {
return false;
}
return false;
}
You have not initialized toTime and fromTime objects before using them. So better call toTime = Calendar.getInstance(); before.
private Calendar fromTime;
private Calendar toTime;
private Calendar currentTime;
public boolean checkTime(String time) {
try {
String[] times = time.split("-");
String[] from = times[0].split(":");
String[] until = times[1].split(":");
fromTime = Calendar.getInstance();
fromTime.set(Calendar.HOUR, Integer.valueOf(from[0]));
fromTime.set(Calendar.MINUTE, Integer.valueOf(from[1]));
toTime = Calendar.getInstance();
toTime.set(Calendar.HOUR, Integer.valueOf(until[0]));
toTime.set(Calendar.MINUTE, Integer.valueOf(until[1]));
currentTime = Calendar.getInstance();
currentTime.set(Calendar.HOUR, Calendar.HOUR_OF_DAY);
currentTime.set(Calendar.MINUTE, Calendar.MINUTE);
if(currentTime.after(fromTime) && currentTime.before(toTime)){
return true;
}
} catch (Exception e) {
return false;
}
return false;
}
this
currentTime.set(Calendar.HOUR, Calendar.HOUR_OF_DAY);
currentTime.set(Calendar.MINUTE, Calendar.MINUTE);
Doesn't do what you would like it to do. What it does is set the field HOUR to the value of Calendar.HOUR, which is an arbitrary constant.
You don't need those 2 lines as getInstance returns a Calendar at the current time.
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
Calendar cal = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
//cal.add(Calendar.DATE, 1);
String date = sdf.format(cal.getTime());
String dateStart = date+" "+"11:30:00";
String date2 = sdf.format(cal2.getTime());
String dateStop = date2+" "+"23:00:00";
Calendar calendar = Calendar.getInstance();
String currentTime = format.format(calendar.getTime());
Date d1 = null;
Date d2 = null;
Date d3 = null;
try {
d1 = format.parse(dateStart);
d2 = format.parse(dateStop);
d3 = format.parse(currentTime);
// Toast.makeText(getApplicationContext(),""+dateCal,Toast.LENGTH_SHORT).show();
if (d3.before(d2)
&& d3.after(d1) ){}else{} } catch (ParseException e) {
e.printStackTrace();
}
Put currentTime outside of setTime and remove if-statement from setTime.
If you need put if-statement outside of setTime.
private boolean checkBedTime(String time) {
// Time Pattern Like : "06:00-19:00"
String[] times = time.split("-");
String[] from = times[0].split(":");
String[] until = times[1].split(":");
int fromHour = Integer.parseInt(from[0]);
int fromMinute = Integer.parseInt(from[1]);
int toHour = Integer.parseInt(until[0]);
int toMinute = Integer.parseInt(until[1]);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
int currentHour = calendar.get(Calendar.HOUR_OF_DAY);
int currentMinute = calendar.get(Calendar.MINUTE);
int convertedFromMinute = (fromHour * 60) + fromMinute;
int convertedToMinute = (toHour * 60) + toMinute;
int convertedCurrentMinute = (currentHour * 60) + currentMinute;
if (convertedFromMinute == convertedToMinute) {
Toast.makeText(context, "Sleep Time & Wake Up Time can't be same", Toast.LENGTH_SHORT).show();
return false;
} else if (convertedToMinute < convertedFromMinute) {
convertedToMinute = convertedToMinute + (24 * 60);
}
Log.v("Time", "FromMinute --> " + convertedFromMinute);
Log.v("Time", "ToMinute --> " + convertedToMinute);
Log.v("Time", "CurrentMinute -- > " + convertedCurrentMinute);
if (convertedCurrentMinute >= convertedFromMinute && convertedCurrentMinute <= convertedToMinute) {
return true;
} else {
return false;
}
}

Categories