Joda Time cannot subtract one hour - java

In my android program, I have a spinner that allows the user to select different times. Each selection is processed with Joda time to subtract the minutes. It works fine for minutes 0 to 59 and 61 and greater. However, when 60 minutes is subtracted, the time is not updated, and the original time is shown.
How do I get Joda time to subtract 60 minutes?
Spinner:
public class MyOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent, View view, int pos,
long id1) {
String mins = parent.getItemAtPosition(pos).toString();
int intmins=0;
// process user's selection of alert time
if(mins.equals("5 minutes")){intmins = 5;}
if(mins.equals("10 minutes")){intmins = 10;}
if(mins.equals("20 minutes")){intmins = 20;}
if(mins.equals("30 minutes")){intmins = 30;}
if(mins.equals("40 minutes")){intmins = 40;}
if(mins.equals("50 minutes")){intmins = 50;}
if(mins.equals("60 minutes")){intmins = 60;}
if(mins.equals("120 minutes")){intmins = 120;}
String stringMinutes=""+intmins;
setAlarm(intmins, stringMinutes);
} else {
}
public void onNothingSelected(AdapterView parent) {
mLocationDisplay.setText(" " + location);
}
}
public void setAlarm(int intmins, String mins) {
// based alarm time on start time of event. TODO get info from database.
String currentDate;
SimpleDateFormat myFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date date1 = null;
DateTime dt;
currentDate = eventdate + " " + startTimeMilitary;// startTimeMilitary;
try {
date1 = myFormat.parse(currentDate);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
dt = new DateTime(date1);
long dateInMillis = dt.getMillis();
String sDateInMillis = Long.toString(dateInMillis);
// subtract the selected time from the event's start time
String newAlertTime = subtractTime(dt, intmins);
newAlertTime = subtractTime(dt, intmins);
//......}
public String subtractTime(DateTime dt, int minusTime) {
DateTime greaterDate;
greaterDate = dt.minusMinutes(minusTime);
// newAlertTime is in UTC format
String newAlertTime = greaterDate.toString();
long alertInMillis = greaterDate.getMillis();
String sAlertInMillis = Long.toString(alertInMillis);
// ////new alert time is a stirng
setStringAlertInMillis(sAlertInMillis);
return newAlertTime;
}

1) Remove hardcode.
Use
final String mins = parent.getItemAtPosition(pos).toString();
final Pattern minutes = Pattern.compile("([0-9]+) minutes");
final Matcher m = minutes.matcher(mins);
String stringMinutes = "0";
if (mins.matches())
{
stringMinutes = m.group(1);
}
setAlarm(Integer.parseInt(stringMinutes), stringMinutes);
instead of your hardcode
String mins = parent.getItemAtPosition(pos).toString();
// your hardcode is here
setAlarm(Integer.parseInt(stringMinutes), stringMinutes);
2) Use DateTimeFormatter instead of SimpleDateFormatter
You get java Date using SimpleDateFormatter and create DateTime by this date.
DateTimeFormatter formatter = DateTimeFormat.forPattern("MM/dd/yyyy HH:mm:ss");
dt = formatter.parseDateTime(currentDate);
3) Joda works well
in this code no problem with Joda.
String subtractTime(DateTime dt, int minusTime)
should works well.
Debug you code, problem is before
if(mins.equals("5 minutes")){intmins = 5;}
if(mins.equals("10 minutes")){intmins = 10;}
//...

Related

Converting String to XMLGregorianCalender timezone offset in java

I am recieving a String of date and zoneAdjustment. I was able to convert the date to gregorian calender but I was wondering how can I set the custom offset that I am recieving.
I am recieving:
String inputDate= "2022-05-19T20:21:11"
String offset = "-PT5H0M";
I need final output as "2020-05-19T20:21:11.000-05:00"
I need to convert the offset to int and use it to set the timezone.
public XMLGregorianCalendar getXmlGregorianCalender(String inputDate, int offset) {
XMLGregorianCalendar xmlGregorianCalendar = null;
try {
Date date;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
date = simpleDateFormat.parse(inputDate);
GregorianCalendar gregorianCalendar =
(GregorianCalendar) GregorianCalendar.getInstance();
gregorianCalendar.setTime(date);
xmlGregorianCalendar =
DatatypeFactory.newInstance().newXMLGregorianCalendar(gregorianCalendar);
xmlGregorianCalendar.setTimezone(offset);
// xmlGregorianCalendar.setTimezone();
} catch (Exception e) {
LOGGER.error("Error parsing dates", e);
}
return xmlGregorianCalendar;
}
I am answering my own question:
public int stringToMinutes(String offset) {
int totalMinute = 0;
String hourString = offset.substring(offset.indexOf("T") + 1, offset.indexOf("H"));
int hour = Integer.parseInt(hourString);
String minuteString = offset.substring(offset.indexOf("H") + 1, offset.indexOf("M"));
int minute = Integer.parseInt(minuteString);
if (offset.contains("-")) {
totalMinute = -((hour * 60) + minute);
} else {
totalMinute = ((hour * 60) + minute);
}
return totalMinute;
}

calculate the price with two same dates but different input data formats

I have the requirement to calculate the price with two same dates but different input data formats. I am hoping for the same result. How can make the below-mentioned code so that output should be the same?
Sample code-calculation
String str="14-04-2021"; // Current date.
SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy");
Date startDate = df.parse(str);
output while pricing logic calculation = 43.06
Date date = new Date(); // System date.
while calculating some price logic = 42.904
public double getCalculatedProductTotalPriceBasedOnRdd(double prdTotalPrice, String pPMAnnualNetPrice, String rdd) throws ParseException {
Date startDate;
if (null != rdd) {
//startDate=new Date();
SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy");
startDate = df.parse(rdd);
} else {
startDate = new Date();
}
Calendar cal = Calendar.getInstance();
cal.setTime(startDate);
cal.set(Calendar.MILLISECOND, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.HOUR, 0);
Date sDate=cal.getTime();
int year = cal.get(Calendar.YEAR);
cal.set(Calendar.YEAR, year);
int days = calculateDaysBetweenTwoDates(startDate);
boolean leapYear = cal.getActualMaximum(Calendar.DAY_OF_YEAR) > 365;
if (null != pPMAnnualNetPrice) {
if (leapYear) {
prdTotalPrice = (Double.parseDouble(pPMAnnualNetPrice) * days) / 366;
} else {
prdTotalPrice = (Double.parseDouble(pPMAnnualNetPrice) * days) / 365;
}
}
return prdTotalPrice;
}
Start using new java.time APIs, instead of old java.util.Date. There is a good article about this.
Following is the demo code:
public class Test {
public static void main(String[] args) throws Exception {
double price = calculate(42.0, "147", "14-04-2021");
System.out.println(price);
price = calculate(42.0, "147", null);
System.out.println(price);
}
static double calculate(double prdTotalPrice, String pPMAnnualNetPrice, String rdd) {
LocalDate startDate;
if (null != rdd) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
startDate = LocalDate.parse(rdd, formatter);
} else {
startDate = LocalDate.now();
}
// int days = calculateDaysBetweenTwoDates(startDate);
int days = startDate.getDayOfYear();
boolean leapYear = startDate.isLeapYear();
if (null != pPMAnnualNetPrice) {
if (leapYear) {
prdTotalPrice = (Double.parseDouble(pPMAnnualNetPrice) * days) / 366;
} else {
prdTotalPrice = (Double.parseDouble(pPMAnnualNetPrice) * days) / 365;
}
}
return prdTotalPrice;
}
}
Output:
41.88493150684931
41.88493150684931
Fix, improve the code as per your needs.

How to create an updating value to Label in JavaFX?

im new to Java and JavaFX and I want to create a GUI with a Label which shows the current system Time.
The Problem is: the Time Value doesn't update. So I wanted to create a Thread, that is updating my Time-Value and also the Label every 1 second with the command:
label_time_show.setText(curTime);
In the inizialize method (see code below) the "label_show_time" can be inizialized with any value, but when I try to setText in an other method I get the following Error:
Exception in thread "Thread-4" java.lang.NullPointerException
I commented the line in the Code where the Label is null and where the Label is NOT null.
Can someone help me with this Problem?
public class FXMLDocumentController implements Initializable, Runnable
{
public String curTime; // <--- main value of time (String)
#FXML
private Label label_time_show;
#FXML
private Label label_time;
// initializer
#Override
public void initialize(URL url, ResourceBundle rb)
{
java.util.Date now = new java.util.Date();
Long sysTime = now.getTime();
String sysTimeString = sysTime.toString();
Integer h = now.getHours();
Integer m = now.getMinutes();
Integer s = now.getSeconds();
String hh = h.toString();
String mm = m.toString();
String ss = s.toString();
curTime = hh + ":" + mm + ":" + ss;
label_show_time.setText(curTime); // <---- label_show_time is NOT null
}
// run method
#Override
public void run()
{
System.out.println("THREAD FXMLController running....");
while(true)
{
time();
}
}
public void time()
{
java.util.Date now = new java.util.Date();
Long sysTime = now.getTime();
String sysTimeString = sysTime.toString();
Integer h = now.getHours();
Integer m = now.getMinutes();
Integer s = now.getSeconds();
String hh = h.toString();
String mm = m.toString();
String ss = s.toString();
curTime = hh + ":" + mm + ":" + ss;
label_show_time.setText(curTime); // <---- label_show_time is null !!! throws ERROR
}
}
So, given the limited information, I'll take a blind stab at this. At the end of your initialize method your label is not null, so start your thread then.
public void initialize(URL url, ResourceBundle rb)
{
//java.util.Date now = new java.util.Date();
//Long sysTime = now.getTime();
//String sysTimeString = sysTime.toString();
//Integer h = now.getHours();
//Integer m = now.getMinutes();
//Integer s = now.getSeconds();
//String hh = h.toString();
//String mm = m.toString();
//String ss = s.toString();
//curTime = hh + ":" + mm + ":" + ss;
//label_show_time.setText(curTime); // <---- label_show_time is NOT null
//Since the label not null here, start your thread here.
new Thread(this).start();
}
Then your time method would be similar except you would post things to the Platform thread.
public void time()
{
java.util.Date now = new java.util.Date();
Long sysTime = now.getTime();
String sysTimeString = sysTime.toString();
Integer h = now.getHours();
Integer m = now.getMinutes();
Integer s = now.getSeconds();
String hh = h.toString();
String mm = m.toString();
String ss = s.toString();
curTime = hh + ":" + mm + ":" + ss;
Platform.runLater(()->{
label_show_time.setText(curTime);
});
}
You might want to put a sleep in your run method since you only need to update every second.
public void run(){
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
while (true){
Date date = new Date();
label_show_time.setText(dateFormat.format(date));
try{
TimeUnit.SECONDS.sleep(1);
}catch(InterruptedException e){
}
}
}
mb it helps you?
and init your label.
update:
public void initialize(URL url, ResourceBundle rb) {
...
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
new Thread(new Runnable() {
#Override
public void run() {
while (true){
Date date = new Date();
System.out.println(dateFormat.format(date));
try{
TimeUnit.SECONDS.sleep(1);
}catch(InterruptedException e){
}
}
}
}).start();
}

Android check days between two day-times

Hello everyone i try to check between days two daytimes
i have for example 12/10/2014 and 12/15/2015 datetimes.I wrote some code witch can to check different days between there two daytimes
this is a my source
public String getDateDiffString(Date dateOne, Date dateTwo) {
long timeOne = dateOne.getTime();
long timeTwo = dateTwo.getTime();
long oneDay = 1000 * 60 * 60 * 24;
long delta = (timeTwo - timeOne) / oneDay;
if (delta > 0) {
return String.valueOf(delta);
} else {
delta *= -1;
return String.valueOf(delta);
}
}
this code working perfect but i want to increase days for example 12/10/2014, 12/11,2014.....12/20/2014 between first and second daytimes.i i also wrote code but result is between first date and second days -1(between 12/19/2014)
this is a my source
SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy");
Date _d;
try {
SimpleDateFormat new_df = new SimpleDateFormat("d MMM");
_d = df.parse(timeInfo.getTimeformat().get(0));
Date _d1 = df.parse(timeInfo.getEndTimeFormat().get(0));
String datetimeis = getDateDiffString(_d1, _d);
int differentdays = Integer.parseInt(datetimeis);
Log.e("Different is ", "" + differentdays);
for (int k = 0; k < differentdays; k++) {
String datetimeformat = dateFormatter(timeInfo.getStartTimePeriod().get(0));
Date datetime = new_df.parse(datetimeformat);
Calendar cal = Calendar.getInstance();
cal.setTime(datetime);
cal.add(Calendar.DATE, k);
datetime = cal.getTime();
String ttime = new_df.format(datetime);
ApishaDaysAdapter.add(ttime);
ApishaHollsAdapter.add(timeInfo.getHole());
String start_time = timeInfo.getTime();
start_time = start_time.replace(",", "\n");
ApishaTimesAdapter.add(start_time);
timeInfo.setStartTimePeriod(ttime);
System.out.println(ttime);
}
} catch (ParseException e) {
e.printStackTrace();
}
}
how i can solve my problem?if anyone knows solution please help me
i want to increase days [12 -20] and not [12-19)

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