Get The Last Number of the Clock Time as Integer - android

What im asking here is Not very commons & im Not even sure if this is Possible,
I know How to get the Current Device Time by using this Code(return as a String) :
SimpleDateFormat Date = new SimpleDateFormat("hh:mm");
String DateTime = Date.format(new Date());
What im looking for is to Get the Last Number of the Minute as an Integer,
Eg. : The Time is 7:24 So i want to get the 4(Last Number) as an Integer,
It is Possible, if so, How ?

Alternatively you could work without using the SimpleDateFormat, but with the Calendar
int lastDigit = Calendar.getInstance().get(Calendar.MINUTE) % 10;
int lastDigit = Data.getDate().getMinutes % 10; // deprecated

I don't have much reputation to answer it in comments but i think what you have to do is get seconds in a variable and create sub-string and convert that string into integer.

I will Answer myself, the Solution was very simple :
SimpleDateFormat Date = new SimpleDateFormat("hh:mm");
String DateTime = Date.format(new Date());
int integer= Integer.parseInt(DateTime.substring(DateTime.length() - 1));
Toast.makeText(this, String.valueOf(integer), Toast.LENGTH_LONG).show();
Thanks

dateTime.substring(dateTime.length() - 1, dateTime.length())
*Side note - the convention for Java variable names is to start with a lower case letter. You have used upper case for the first letter in your variable names. Date.format may cause confusion to some people as it looks like a reference to a static method in the Date class.

Try this:
int lastMin = (int)((System.currentTimeMillis()/60000l) % 10);
Gives me 7 at 16:17 o'clock

Related

How to Convert "2021-05-14T13:42:48.000Z" string to Date Object?

I am trying to convert "2021-05-14T13:42:48.000Z" string to Date Object.
I have tried this:
DateFormat dateFormat = new SimpleDateFormat("YYYY-MM-DDHH:MM:SS");
And also this, which i saw on stackoverflow only:-
DateFormat dateFormat = new SimpleDateFormat("YYYY-MM-DD'T'HH:MM:SS'A'");
But none of it worked.
How can i convert this string to my date object?
Assuming your date string always represents a UTC time (with the 'Z'), you can use format string:
yyyy-MM-dd'T'HH:mm:ss.SSSZ
but you'll first need to replace the Z in your date string with the fixed timezone "+0000", as in "2021-05-14T13:42:48.000+0000".
Try this:
String myDateString = "2021-05-14T13:42:48.000Z"
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ", Locale.US);
Date myDate = dateFormat.parse (myDateString.replace("Z","+0000"));
This will return a date correctly adjusted for your current timezone, in my case 9:42:48am EDT.
There is a more detailed discussion at Converting ISO 8601-compliant String to java.util.Date which you may find useful.
You have used the date-time format incorrectly. It's important to note that the date-time formats have different meanings between capitalized and small letters.
For example: Capital MM means months, whereas small mm means minutes.
To know more about the date formats, you can refer this:
https://cheatography.com/pezmat/cheat-sheets/date-time-formats/pdf/
or this:
https://devhints.io/datetime
And the answer for your case is:
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
Please do not use SimpleDateFormat or even java.date. All these classes are deprecated.
Instead, rely on the Android available java.time package.
In short:
val source = "2021-05-14T13:42:48.000Z"
val parsed = ZonedDateTime.parse(source)
This will correctly parse the timezone (Z for Zulu/UTC/GMT).
You can verify this, by simply converting the parsed Zoned date time into, for example, Europe/Amsterdam time (which is +2).
val source = "2021-05-14T13:42:48.000Z"
val parsed = ZonedDateTime.parse(source)
parsed.toString() // prints: 2021-05-14T13:42:48Z
parsed.zone // prints: "Z"
ZoneId.of(parsed.zone.id) // returns the ZoneOffset "Z" (correct)
// Convert to Amsterdam Time
val amsterdamDateTime = parsed.withZoneSameInstant(ZoneId.of("Europe/Amsterdam"))
amsterdamDateTime.toString() // prints: 2021-05-14T15:42:48+02:00[Europe/Amsterdam] (2 hours ahead of the Zulu time, also correct).
parsed.format(DateTimeFormatter.ISO_DATE_TIME).toString() // Prints: 2021-05-14T13:42:48Z (correct)
So as you can see, these classes do the right thing (most of the time).
I suggest you use them.

Same Milliseconds values coming for different dates

I store my values in database by converting the date value in milliseconds,so to get the latest date on top by using order by desc query. The order is coming as required but if i enter date 02/01/2016 and 01/30/2016 both are storing same milliseconds value.
String date = "02/01/2016";
String month = date.substring(0, 2);
String day = date.substring(3, 5);
String year = date.substring(6, 10);
Calendar c1 = Calendar.getInstance();
c1.set(Integer.parseInt(year), Integer.parseInt(month), Integer.parseInt(day));
long left = c1.getTimeInMillis();
After debugging i got the following milliseconds values
02/01/2016----61414914600000
and 01/30/2016----61414914600000
Anybody knows why this happening?
Using SimpleDateFormat value I am getting different milliseconds value:
Date date;
String dtStart = "02/01/2016";
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
try {
date = format.parse(dtStart);
long timeMills=date.getTime();
System.out.println("Date ->" + date);
} catch (Exception e) {
e.printStackTrace();
}
I ran your initial code and it functions almost as expected. A few points:
You mention millisecond 61414914600000. That's not correct because it's 1900 years into the future:
http://currentmillis.com/?61414914600000
I'm pretty sure you got that number from a Date object, not from a Calendar: http://docs.oracle.com/javase/6/docs/api/java/util/Date.html#Date(int, int, int)
As Mat said the month is zero-based for Calendar and the line where you call the setter should subtract 1:
c1.set(Integer.parseInt(year), Integer.parseInt(month) - 1, Integer.parseInt(day));
You answered your own question with another snippet of code but Date is deprecated, Calendar should be used instead. Your original code in the initial post was essentially correct (except the zero-based month). You should make sure that you know where your output is coming from and / or that you don't forget to build the code before running it.

Android - Time Comparison "hh:mm:ss a" format

"I try to compare two time in "hh:mm:ss a" format. But it not really work in what I think. I googled but couldn't find a proper answer. Sorry cause I'm new to programming."
I try to compare the time like this:
String strSQL = "SELECT * FROM " + TABLE_SCHEDULE + " WHERE lecturer_id=? AND schedule_day=? AND schedule_endtime > ?";
schedule_endtime > ?
However, the comparison has ignored the AM/PM which caused the result become like this:
eg. 12:00:00 PM is bigger than 02:00:00 PM.
Hope that you all can give some tips or provide some solution. Appreciate it.
Instead of comparing the formatted string, compare the value in milliseconds. Take a look at this to convert the string back to date:
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
String dateInString = "7-Jun-2013";
try {
Date date = formatter.parse(dateInString);
System.out.println(date);
System.out.println(formatter.format(date));
} catch (ParseException e) {
e.printStackTrace();
}
Then once you have two dates you can compare them like so:
boolean before = someDate.before(anotherDate);
or
boolean after = someDate.after(anotherDate);
or even
someDate.getTime() < anotherDate.getTime();
Side note: when I store dates, I like to just store the millisecond value and the time zone. That way you don't need to worry about things like this.
Inside the SQLite database you are storing the dates as Strings, not as a Date because in SQLite doesn't exist a Date type (https://www.sqlite.org/datatype3.html).
You have two options: change the column type to a INTEGER type and store de date as a number (then you can compare milliseconds) or get the entity as it is, parse a Date type with the String, create a SimpleDateFormat with the given format and then make the comparison.

Formatting Long value to Date String?

I am working on an application in which I have to convert a long value to a Date string and display. To achieve the purpose I am using following function, but it is returning me the date from 70's and 80's obviously not appropriate. I am using the following finction:
public static String convertDateFromLongToCompleteString(long date) {
Date d = new Date(date * 1000);
SimpleDateFormat dateformat = new SimpleDateFormat("dd/MM/yyyy hh:mm a");
String formattedDateFromLong = dateformat.format(d);
return formattedDateFromLong;
}
The long value is just simply System.currentTimeMillis() and when I have to show it to the user, I have to format that for which I am using above function. I have checked system and device dates, their zones and time, everything is just fine. Please update that why is this issue appearing and how can I get the exact date. Thanks!
Edit
I have also tried withoout multiplication with 1000, it gives me time and date from 1970.
If your long date is simply System.currentTimeMillis(), then multiplication with 1000 is not required.
Date d = new Date(date);
Replace Date d = new Date(date * 1000); with Date d = new Date(date);
In case you're using the above method only with System.currentTimeMillis(), you can call Date constructor without any parameters, it will give you the Date object that refers to the current date and time. This will be an easier way to solve your problem. Hope this helps.

Calendar giving me the wrong hour and minute

I am trying to get the time of a timestamp but I keep getting the wrong time when I use Calendar.HOUR and Calendar.MINUTE,no matter what the timestamp is it tells me the hour is 10 and the minute is 12.
now when I use the Calendar.getTime() it gives me the correct time so I dont understand? I just want to get the hour in 12hr format and the minute
here is how i go about doing it
public static String getRealTime(long time){
Calendar cal = Calendar.getInstance();
Log.d("Calendar",String.valueOf(time));
cal.setTimeInMillis(time);
Date timeS = cal.getTime();
String sTime = timeS.toString(); // gives correct time in 24hr format
int hr = cal.HOUR; // gives me 10 no matter what the timestamp is
int min = cal.MINUTE; // gives me 12 no matter what the timestamp is
String dMin = getDoubleDigit(min);
int ampm = cal.AM_PM;
String m = new String();
if(ampm == 0){
m = "AM";
}else{
m="PM";
}
String rtime = String.valueOf(hr)+":"+dMin+" "+m;
return rtime;
}
so say the timestamp is 1316626200000 cal.getTime() gives me Wed Sep 21 13:30:00 EDT 2011 which would be the correct time but cal.HOUR gives me 10 for the hour which clearly is not what it should be. Why is it doing that?
cal.HOUR and cal.MINUTE are static final Integers for use in Calendar method calls. You would use this code to get the correct result:
int hr = cal.get(Calendar.HOUR);
int min = cal.get(Calendar.MINUTE);
Notice that I called the HOUR and MINUTE fields from Calendar and not your object cal. It is bad practice to call static members from an instantiated object.
The great and almighty Android Reference page to the rescue!!! :D http://developer.android.com/reference/java/util/Calendar.html
So, here's the lowdown on why some of those things aren't returning the results you are expecting. First off, the Calendar.HOUR is not a reference to the current hour. First hint at that is the fact that it is in all caps, which by Java convention means that this is a constant (aka final) field. If you are developing in Eclipse it probably brought up a warning saying that you should probably reference the static variable with the class name Calendar instead of using the instance cal. Second hint: the reference page said so! ;)
Well, what should you do with the Calendar.HOUR then? That is a static constant so that you can use the cal.get() to find out. (see the reference page http://developer.android.com/reference/java/util/Calendar.html#get(int))
But! There is an easier way. The code that you might be looking for could be something like this:
public static String getRealTime(long time){
return new SimpleDateFormat("HH:mm").format(new Date(time));
//if you'd rather have the current time, just use new Date() without the time as a parameter
}
Another user has asked for a sorta similar things and there are a few other implementations on this page Display the current time and date in an Android application

Categories

Resources