Operator '<' cannot be applied to 'java.lang.String' - java

i got the system time in a string for example something like "1240".
then i wanted to do something like if the system time was < than 1240,then close the application.
but it gives me the "Operator '<' cannot be applied to java.lang.String!" Error!
My code is :
runOnUiThread(new Runnable() {
public void run() {
try{
TextView txtCurrentTime= (TextView)findViewById(R.id.showtime);
Date dt = new Date();
int hours = dt.getHours();
int minutes = dt.getMinutes();
int mynum = 1240;
String curTime = hours + "" + minutes;
txtCurrentTime.setText(curTime);
if(curTime < mynum ){
System.exit(0);
}
}catch (Exception e) {}
}
});
What's the problem?

try{
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
String str1 = String.valueOf(hours1) + ":" + String.valueOf(minutes1) + ":" + "00";
String str2 = String.valueOf(hours2) + ":" + String.valueOf(minutes2) + ":" + "00";
Date date1 = formatter.parse(str1);
Date date2 = formatter.parse(str2);
if (date1.compareTo(date2)<0)
{
// if date2 > date1
}
}catch (ParseException e1){
e1.printStackTrace();
}
formats for dates
check date/time format as per your requirement from here

< is not defined for a string and an int of course . So you can't use it .
your current time can be calculated like this :
int curTime = 100*hours + minutes;
then you can use < between two integers.
I believe though you must use System Milliseconds which is more usual.

if(hours * 100 + minutes < mynum){
System.exit(0);
}

Related

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();
}

java parse date time with milliseconds into date getting parse error

I have a string in which I am finding the datetime with milliseconds as follows:
Calendar now = Calendar.getInstance();
int year = now.get(Calendar.YEAR);
int month = now.get(Calendar.MONTH) + 1; // Note: zero based!
int day = now.get(Calendar.DAY_OF_MONTH);
int hour = now.get(Calendar.HOUR_OF_DAY);
int minute = now.get(Calendar.MINUTE);
int second = now.get(Calendar.SECOND);
int millis = now.get(Calendar.MILLISECOND);
String monthup = String.valueOf(month);
String dayup = String.valueOf(day);
String hourup = String.valueOf(hour);
String minuteup = String.valueOf(minute);
String secondup = String.valueOf(second);
String millisup = String.valueOf(millis);
if(monthup.length()==1){monthup="0"+monthup;}
if(dayup.length()==1){dayup="0"+dayup;}
if(hourup.length()==1){hourup="0"+hourup;}
if(minuteup.length()==1){minuteup="0"+minuteup;}
if(secondup.length()==1){secondup="0"+secondup;}
if(millisup.length()==1){millisup="0"+millisup;}
if(millisup.length()==2){secondup="00"+millisup;}
String timewithmilsec = year+ monthup + dayup+ hourup+ minuteup+ secondup+ millisup;
System.out.println(timewithmilsec);
I am getting a value: 20151020115216690 which is obviousely correct.
I want to parse it to java Date format.
What I did is as follows:
try{
DateFormat formatter = new SimpleDateFormat("yyyyMMdHHmmssaaa");
Date date = formatter.parse(timewithmilsec);
System.out.println(date);
}
catch(Exception e){
System.out.println(e);
}
I am getting an error as follows:
java.text.ParseException: Unparseable date: "20151020115247995"
You have only one d in your format, but are padding the day to two characters, also, according to the JavaDocs...
a Am/pm marker Text PM
which isn't a millisecond place holder, I think you mean SSS
For example...
Calendar now = Calendar.getInstance();
int year = now.get(Calendar.YEAR);
int month = now.get(Calendar.MONTH) + 1; // Note: zero based!
int day = now.get(Calendar.DAY_OF_MONTH);
int hour = now.get(Calendar.HOUR_OF_DAY);
int minute = now.get(Calendar.MINUTE);
int second = now.get(Calendar.SECOND);
int millis = now.get(Calendar.MILLISECOND);
String monthup = String.valueOf(month);
String dayup = String.valueOf(day);
String hourup = String.valueOf(hour);
String minuteup = String.valueOf(minute);
String secondup = String.valueOf(second);
String millisup = String.valueOf(millis);
if (monthup.length() == 1) {
monthup = "0" + monthup;
}
if (dayup.length() == 1) {
dayup = "0" + dayup;
}
if (hourup.length() == 1) {
hourup = "0" + hourup;
}
if (minuteup.length() == 1) {
minuteup = "0" + minuteup;
}
if (secondup.length() == 1) {
secondup = "0" + secondup;
}
if (millisup.length() == 1) {
millisup = "0" + millisup;
}
if (millisup.length() == 2) {
secondup = "00" + millisup;
}
String timewithmilsec = year + monthup + dayup + hourup + minuteup + secondup + millisup;
System.out.println(timewithmilsec);
try {
DateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmssSSS");
Date date = formatter.parse(timewithmilsec);
System.out.println(date);
} catch (Exception e) {
System.out.println(e);
}
Which for me prints
20151020173034124
Tue Oct 20 17:30:34 EST 2015
And while I'm at it, let me introduce you to String.format, which can reduce all you int to String conversion and padding code down to...
String timewithmilsec = String.format("%04d%02d%02d%02d%02d%02d%03d", year, month, day, hour, minute, second, millis);
I am getting Tue Oct 20 12:04:08 IST 2015 but interestingly I did not see any millisecond here
Date#toString won't include the milliseconds by default, you will need to supply a DateFormat which can.
If I replace the last System.out.println with System.out.println(new SimpleDateFormat("dd MMM yyyy HH:mm:ss.SSS").format(date)); it prints something like
20 Oct 2015 17:37:14.856
(for the value 20151020173714856)
According to documentation letter S responds to milliseconds so your format should look like this new SimpleDateFormat("yyyyMMddHHmmssSSS"); (you have one d in your format).
The answer is the missing "d" in the date format, where #MadProgrammer depicts.
In addition, the generation of the string representation of the date should be reconsidered. You should use SimpleDateFormat.format() to generate date string as in the sample code below:
Calendar now = Calendar.getInstance();
DateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmssSSS");
String formattedDate = formatter.format(now.getTime());
System.out.println("Formatted date: " + formattedDate);
And the output will be in a format that you requested.
Formatted date: 20151020094934279

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)

Converting Youtube Data API V3 video duration to hh:mm:ss format in java?

I am using Youtube data api v3 to get video information like title, views count and duration.The duration value is new to me as it's an ISO8601 date which I need to convert to a readable format like hh:mm:ss. Duration can have the following different values:
PT1S --> 00:01
PT1M --> 01:00
PT1H --> 01:00:00
PT1M1S --> 01:01
PT1H1S --> 01:00:01
PT1H1M1S --> 01:01:01
I could use Joda Time library to parse the value and calculate the duration in seconds but the library is of 500kb in size which will increase the size of my application that I don't want.
look at this code :
private static HashMap<String, String> regexMap = new HashMap<>();
private static String regex2two = "(?<=[^\\d])(\\d)(?=[^\\d])";
private static String two = "0$1";
public static void main(String[] args) {
regexMap.put("PT(\\d\\d)S", "00:$1");
regexMap.put("PT(\\d\\d)M", "$1:00");
regexMap.put("PT(\\d\\d)H", "$1:00:00");
regexMap.put("PT(\\d\\d)M(\\d\\d)S", "$1:$2");
regexMap.put("PT(\\d\\d)H(\\d\\d)S", "$1:00:$2");
regexMap.put("PT(\\d\\d)H(\\d\\d)M", "$1:$2:00");
regexMap.put("PT(\\d\\d)H(\\d\\d)M(\\d\\d)S", "$1:$2:$3");
String[] dates = { "PT1S", "PT1M", "PT1H", "PT1M1S", "PT1H1S", "PT1H1M", "PT1H1M1S", "PT10H1M13S", "PT10H1S", "PT1M11S" };
for (String date : dates) {
String d = date.replaceAll(regex2two, two);
String regex = getRegex(d);
if (regex == null) {
System.out.println(d + ": invalid");
continue;
}
String newDate = d.replaceAll(regex, regexMap.get(regex));
System.out.println(date + " : " +newDate);
}
}
private static String getRegex(String date) {
for (String r : regexMap.keySet())
if (Pattern.matches(r, date))
return r;
return null;
}
The regex2two has been used to add a leading zero0 to 1-digit numbers. you can try this demo.
In the regexMap I'v stored all 7 cases and appropriate regex-replace.
I did by myself
Let's try
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.
public class YouTubeDurationUtils {
/**
*
* #param duration
* #return "01:02:30"
*/
public static String convertYouTubeDuration(String duration) {
String youtubeDuration = duration; //"PT1H2M30S"; // "PT1M13S";
Calendar c = new GregorianCalendar();
try {
DateFormat df = new SimpleDateFormat("'PT'mm'M'ss'S'");
Date d = df.parse(youtubeDuration);
c.setTime(d);
} catch (ParseException e) {
try {
DateFormat df = new SimpleDateFormat("'PT'hh'H'mm'M'ss'S'");
Date d = df.parse(youtubeDuration);
c.setTime(d);
} catch (ParseException e1) {
try {
DateFormat df = new SimpleDateFormat("'PT'ss'S'");
Date d = df.parse(youtubeDuration);
c.setTime(d);
} catch (ParseException e2) {
}
}
}
c.setTimeZone(TimeZone.getDefault());
String time = "";
if ( c.get(Calendar.HOUR) > 0 ) {
if ( String.valueOf(c.get(Calendar.HOUR)).length() == 1 ) {
time += "0" + c.get(Calendar.HOUR);
}
else {
time += c.get(Calendar.HOUR);
}
time += ":";
}
// test minute
if ( String.valueOf(c.get(Calendar.MINUTE)).length() == 1 ) {
time += "0" + c.get(Calendar.MINUTE);
}
else {
time += c.get(Calendar.MINUTE);
}
time += ":";
// test second
if ( String.valueOf(c.get(Calendar.SECOND)).length() == 1 ) {
time += "0" + c.get(Calendar.SECOND);
}
else {
time += c.get(Calendar.SECOND);
}
return time ;
}
}
Had to deal with this problem as well. I had to convert the length to milliseconds, but once you get the secs/mins/hours variables populated you can convert to any format you want:
// Test Value
$vidLength = 'PT1H23M45S';
$secs = '';
$mins = '';
$hours = '';
$inspecting = '';
for($i=(strlen($vidLength)-1); $i>0; $i--){
if(is_numeric($vidLength[$i])){
if($inspecting == 'S'){
$secs = $vidLength[$i].$secs;
}
else if($inspecting == 'M'){
$mins = $vidLength[$i].$mins;
}
else if($inspecting == 'H'){
$hours = $vidLength[$i].$hours;
}
}
else {
$inspecting = $vidLength[$i];
}
}
$lengthInMS = 1000*(($hours*60*60) + ($mins*60) + $secs);
I needed a array of all these converted duration. So I wrote the below as a workaround and also java.time.duration was not working for me, don't know why.
String[] D_uration = new String[10];
while(iteratorSearchResults.hasNext()){String Apiduration1=Apiduration.replace("PT","");
if(Apiduration.indexOf("H")>=0){
String Apiduration2=Apiduration1.replace("H",":");
if(Apiduration.indexOf("M")>=0){
String Apiduration3=Apiduration2.replace("M",":");
if(Apiduration.indexOf("S")>=0){
D_uration[i]=Apiduration3.replace("S","");
}
else{
String Apiduration4=Apiduration2.replace("M",":00");
D_uration[i]=Apiduration4;
}
}
else{
String Apiduration4=Apiduration2.replace(":",":00:");
if(Apiduration.indexOf("S")>=0){
D_uration[i]=Apiduration4.replace("S","");
}
else{
String Apiduration3=Apiduration4.replace(":00:",":00:00");
D_uration[i]=Apiduration3;
}
}
}
else{
if(Apiduration.indexOf("M")>=0){
String Apiduration2=Apiduration1.replace("M",":");
if(Apiduration.indexOf("S")>=0){
D_uration[i]=Apiduration2.replace("S","");
}
else{
String Apiduration4=Apiduration2.replace(":",":00");
D_uration[i]=Apiduration4;
}
}
else{
D_uration[i]=Apiduration1.replace("S","");
}
}
"Apiduration" is returned by the Youtube data Api in ISO8601 format.
Made some edits now i think it should work fine.

How to Disable date ranges in java calendar

In my java project i want to disable a range of dates in the java calendar and could not be successful. I'm using Netbeans as my IDE and JCalendar. Below is my code. Any help would be appreciated.
ArrayList<JSONObject> arrays = new ArrayList<JSONObject>();
for (int i = 0; i < n; i++) {
JSONObject another_json_object = vacation_home_booking_data.getJSONObject(i);
JSONObject[] jsons = new JSONObject[arrays.size()];
arrays.toArray(jsons);
String id = another_json_object.getString("id");
String vh_id = another_json_object.getString("vh_id");
String check_in = another_json_object.getString("check_in");
String check_out = another_json_object.getString("check_out");
String status = another_json_object.getString("status");
//creating two arrays of checking and checkout
//check_in_arr[i] = another_json_object.getString("check_in");
//check_out_arr[i] = another_json_object.getString("check_out");
System.out.println("ID is " + id + "vh id is " + vh_id + "check in is " + check_in + "check out is " + check_out);
DateFormat formatter = new SimpleDateFormat("yyyy-mm-dd");
try {
Date date1 = formatter.parse(check_in);
Date date2 = formatter.parse(check_out);
jCalendar1.setSelectableDateRange(date1, date2);
jCalendar1.setBackground(Color.yellow);
//jCalendar1.setSelectedDate();
} catch (ParseException ex) {
Logger.getLogger(Calender.class.getName()).log(Level.SEVERE, null, ex);
ex.printStackTrace();
}
}
Please see, if the below methods works for you:
private DateChooserCombochooser; // Initialize this somewhere
public void setMaxDate(Calendar aDate) {
chooser.setMaxDate(aDate);
}
public void setMinDate(Calendar aDate) {
chooser.setMinDate(aDate);
}
Alternatively, try using setDefaultPeriods(PeriodSet periods) method in the API.

Categories