How to convert number to hour and minute in android - android

In my application i should show hour and minute and i get this numbers from server with this sample :
Json :
{
data:{
time:84561
}
}
i should get this number from time and show it with this format
**hh : mm : ss**
I can get number of time, but i can't convert this to **hh : mm : ss** .
How can i it?

long timeSec= 84561;// Json output
int hours = (int) timeSec/ 3600;
int temp = (int) timeSec- hours * 3600;
int mins = temp / 60;
temp = temp - mins * 60;
int secs = temp;
String requiredFormat = hours+ ": "+mins+": "+secs;//hh:mm:ss formatted string

Java 9 answer
Duration time = Duration.ofSeconds(87561);
String hms = String.format("%02d : %02d : %02d",
time.toHoursPart(),
time.toMinutesPart(),
time.toSecondsPart());
Unfortunately in Java 8 Duration does not lend itself well to formatting. The methods I use in the snippet are introduced in Java 9 and will calculate the values for hh, mm and ss. Then String.format() does the rest.
I know you cannot use this on Andriod (yet), but I wanted to have this answer stand here for others who can use Java 9, now or in the future.

Very simple
If this is unix time then it will be converted into human readable time format with this snippet.
String relavtiveTimeString = String.valueOf(DateUtils.getRelativeTimeSpanString(unixTime));
You can use new Date(unix); and with below function you can get formatted date. You can format in different style.
//This mehtod convert the date into standard date like : 2017-12-23
public static String getformateDate(Date dateObject) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
return dateFormat.format(dateObject);
}
For more information check this link already answer :
Convert unix time stamp to date in java
Referance:
https://developer.android.com/reference/android/text/format/DateUtils.html
https://developer.android.com/reference/android/text/format/Time.html

Pass your Number or timestamp and convert to milliseconds for hour and minute.use the below code.
public static String getCurrentTimeStamp(String mCurrentTime) {
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy hh:mm a z");
TimeZone tz = TimeZone.getDefault();
format.setTimeZone(tz);
// System.out.println("TimeZone "+tz.getDisplayName(false, TimeZone.SHORT)+" Timezon id :: " +tz.getID());
SimpleDateFormat dateParser = new SimpleDateFormat("dd/MM/yyyy hh:mm a z");
Date dateTime = null;
try {
dateTime = dateParser.parse(format.format(Long.parseLong((mCurrentTime)) * 1000));
Log.e("Starttime", "Starttime" + format.format(dateTime));
return format.format(dateTime);
} catch (ParseException e) {
e.printStackTrace();
return null;
}
}

Try This Logic Use it As per Requirement
public class Test {
public static void main(String[] args) {
String json = "{\n" +
" data:{\n" +
" time:84561\n" +
" }\n" +
"}";
Date date = new Gson().fromJson(json, Date.class);
long milli = date.getTime() * 1000;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss");
System.out.println(simpleDateFormat.format(new java.util.Date(milli)));
}
class Date implements Serializable{
int time;
public int getTime() {
return time;
}
public void setTime(int time) {
this.time = time;
}
}
Output
05:30:00
If you want to download Gson jar download it from
here

Related

Local time to EST time Conversion

Android Local time to EST time Conversion
Code:
SimpleDateFormat serverDateFormat=new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
serverDateFormat.setTimeZone(TimeZone.getTimeZone("EST"));
Calendar calender= Calendar.getInstance(Locale.getDefault());
String time=serverDateFormat.format(calender.getTime());
but i getting wrong time.
one hour difference from right time.
for eg :
local time : Tue Jul 07 17:30:00 GMT+05:30 2015
formated time : 2015/07/07 07:00:00
right time : 2015/07/07 08:00:00
Your problem is using the identifier "EST" which stands for "Eastern Standard Time". As the name suggests it does not use daylight saving rules. Proof:
TimeZone tz = TimeZone.getTimeZone("EST");
long offset = tz.getOffset(System.currentTimeMillis()) / (1000 * 3600);
System.out.println(tz.getID() + ":" + tz.useDaylightTime() + "/" + offset);
// output: EST:false/-5
Use the timezone id "America/New_York" instead:
tz = TimeZone.getTimeZone("America/New_York");
offset = tz.getOffset(System.currentTimeMillis()) / (1000 * 3600);
System.out.println(tz.getID() + ":" + tz.useDaylightTime() + "/" + offset);
// output: America/New_York:true/-4
Then you will observe daylight saving time in July making an offset difference of (+05:30) - (-04:00) = +09:30 resulting in the expected local time 8 AM.
hey please try this function for time conversion -
public static String getTime(String time, SimpleDateFormat sdf) {
String convertedTime = "";
try {
TimeZone timeZone = TimeZone.getDefault();
Date postdate = sdf.parse(time);
long postTimeStamp = postdate.getTime() + timeZone.getRawOffset();
String dateString = sdf.format(new Date(postTimeStamp));
convertedTime = dateString;
// convertedTime = getLastTime(context, time);
} catch (Exception e) {
e.printStackTrace();
}
return convertedTime;
}

Date Functions in Android Client for Azure Mobile Service

I have an Azure Mobile Service which returns date to an Android Client in this format
"Sat Sep 27 22:48:48 PDT 2014"
I want to calculate the difference between this returned date and today's date. After much iterations here is my current function.
public String calculateDayDifference(String DateFromAzure){
SimpleDateFormat AzureDateFormat = new SimpleDateFormat("EEE MMM dd H:m:s yyyy");
Calendar cal = Calendar.getInstance(Locale.getDefault());
String result;
try {
String currentDate = AzureDateFormat.format(System.currentTimeMillis() * 1000L);
Date presentDate = AzureDateFormat.parse(currentDate);
Date billDueDate = AzureDateFormat.parse(DateFromAzure);
long diff = billDueDate.getTime() - presentDate.getTime();
result = Long.toString(diff);
} catch (ParseException e) {
result = Long.toString(- 1);
//e.printStackTrace();
}
return result;
}
And here is how I call this function from my Adapter's getView() method
viewHolder.txtNumberDays.setText(mDateFunctions.calculateDayDifference(
viewHolder.billSummary.getBillDueDate().toString()))
And here is the Java class field that maps to the date column in the Mobile Service table.
#SerializedName("billDueDate")
private Date BillDueDate;
No matter how I tweak it, it give me negative result like so. How can I re-write the method above to return the difference between today's date and the date returned from Azure Mobile Service table?
Ok, from the AMS Android SDK source code I can see that the SDK handles formatting and parsing of dates automatically so what is returned is a valid java.util.date object.
https://github.com/Azure/azure-mobile-services/blob/master/sdk/android/src/sdk/src/com/microsoft/windowsazure/mobileservices/DateSerializer.java
With this realization I just called getTime() method on the returned date so I can compare it again current date which can be obtained from System.CurrentTimeMillis(). I then converted the result to int and that was with. Long learning experience. Its not the most efficient way to handle this but it works for. Here is the code
mBillDueDateService.mBillTable
.execute(new TableQueryCallback<Bill>() {
#Override
public void onCompleted(List<Bill> result, int count,
Exception exception, ServiceFilterResponse response) {
if (exception == null){
for (Bill bill : result){
long timeInLong = bill.getBillDueDate().getTime();
long currentTime = System.currentTimeMillis();
long diffTime = timeInLong - currentTime;
long diffDays = diffTime / (1000 * 60 * 60 * 24);
int daysdiff = (int) diffDays;
Log.i(TAG, "Bill Name " + bill.getBillName() + "" + "Due in " + daysdiff + "days");
bill.setDaysBeforeDueDate(daysdiff);
mUpcomingBillAdapter.add(bill);
}

Convert Date to Year and Month

I am writing an application in which I have to display a date . Now I want to convert that date into Year and Month from the Current Date.
My Date is Like - 29/03/2017.
I want to convert this date into Year and Months.
Sorry I think you are not able to understand my question. I want the Difference of current date and above date in year and months.
Sorry for my explanation.
You can use Joda Time and compute a Period between two LocalDate values (which is what you've got here) using months and years as the units.
example
LocalDate dob = new LocalDate(1992, 12, 30);
LocalDate date = new LocalDate(2010, 12, 29);
Period period = new Period(dob, date, PeriodType.yearMonthDay());
System.out.println(period.getYears() + " years and " +
period.getMonths() + " months");
I found my answer using Calender class .
First i find the difference between two days and using that days i found the years and months.
Here i post my code, which i think help to others.
int days = Integer.parseInt(Utility.getDateDiffString("29/03/2017"));
int years = days/365;
int remainingDays = days - (365*years);
int months = remainingDays/30;
getDateDiffString() Method. In this method we need to pass end date
public static String getDateDiffString(String endDate)
{
try
{
Calendar cal = Calendar.getInstance();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date dateTwo = dateFormat.parse(endDate);
long timeOne = cal.getTimeInMillis();
long timeTwo = dateTwo.getTime();
long oneDay = 1000 * 60 * 60 * 24;
long delta = (timeTwo - timeOne) / oneDay;
if (delta > 0) {
return "" + delta + "";
}
else {
delta *= -1;
return "" + delta + "";
}
}
catch (Exception e)
{
e.printStackTrace();
}
return "";
}
if your date's format is fixed, you can do it like this :
String myDate = "29/03/2017";
String newDate = myDate.subString(6, 10) + "-" + myDate.subString(3, 5)
this method to convert the normal string to date format
String currentDateString = "02/27/2012 17:00:00";
SimpleDateFormat sd = new SimpleDateFormat("mm/dd/yyyy HH:mm:ss");
Date currentDate = sd.parse(currentDateString);
after that you get the formal method
You Should use SimpleDateFormate !
For Example:--- You can get time & Date as you want:-
Date email_date = m.getSentDate();// this is date which you are getting
DateFormat date = new SimpleDateFormat("EEE MMM yyyy");
DateFormat time = new SimpleDateFormat("hh:mm aa");
String date_str=date.format(email_date);
String time_str=time.format(email_date);
Use Java Calendar class to get year from date
Calendar c=Calendar.getInstance();
SimpleDateFormat simpleDateformat=new SimpleDateFormat("yyyy MMM");
System.out.println(simpleDateformat.format(c.getTime()));
To get difference between two date
int diffInDays = (int)( (newerDate.getTime() - olderDate.getTime())
/ (1000 * 60 * 60 * 24) )
long timeDiff = (d1.getTime() - d2.getTime());
String diff=String.format("%d year(s) %d day(s) %d hour(s) %d min(s) %d sec(s)",(TimeUnit.MILLISECONDS.toDays(timeDiff)/365),TimeUnit.MILLISECONDS.toDays(timeDiff)%365,
TimeUnit.MILLISECONDS.toHours(timeDiff)
- TimeUnit.DAYS.toHours(TimeUnit.MILLISECONDS
.toDays(timeDiff)),
TimeUnit.MILLISECONDS.toMinutes(timeDiff)
- TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS
.toHours(timeDiff)),
TimeUnit.MILLISECONDS.toSeconds(timeDiff)
- TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS
.toMinutes(timeDiff)));
System.out.println(diff);
Specify correct date here in d1 & d2.Then you will get right answer of difference
First put your Date into a String variable as:
String dateToConvert = "29/03/2017";
Instantiate Calendar as:
Calendar convertedDate = Calendar.getInstance();
Set that date to calendar
convertedDate.set(dateToConvert);<br/>
Then use this line:
String datePicked = DateFormat.getDateInstance().format(convertedDate.getTime());
Output: Mar 29, 2017

How do you compare the time portion of a time string?

I have in my preferences some strings that represent a start time and and ending time.
I wrote this function to determine if the current time is within the start and ending time. The format of the date strings is "HH:mm". The function takes the strings that are from the preferences.
I'm sure I'm missing some code for the comparing because my parsing returns a something like this:
Thu Sep 29 12:24:33 EDT 2011
But all I need is to get this:
12:24
Here is the function. Can you help me correct the coding?
Thanks.
Truly,
Emad
public static boolean currentTimeIsWithinStartAndEnd(String startTime,
String endTime) {
String pattern = "HH:mm";
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
boolean booleanValueToReturn = false;
try {
Date startTimeToCompare = sdf.parse(startTime);
Date endTimeToCompare = sdf.parse(endTime);
/*
* These are for the current time in date format.
*/
Date currentTime = new Date(System.currentTimeMillis());
Log.w("Emad", "Current Time: " + currentTime + " Start Time is: "
+ startTimeToCompare + " End Time is : "
+ endTimeToCompare);
/*
* Check if current time is equal or greater than the start time.
*/
if (currentTime.compareTo(startTimeToCompare) == 0
|| currentTime.compareTo(startTimeToCompare) == 1) {
booleanValueToReturn = true;
/*
* Now check if the current time is equal or less than the end
* time.
*/
if (currentTime.compareTo(endTimeToCompare) == 0
|| currentTime.compareTo(endTimeToCompare) == -1) {
booleanValueToReturn = true;
} else {
booleanValueToReturn = false;
}
} else {
booleanValueToReturn = false;
}
} catch (java.text.ParseException e) {
}
return booleanValueToReturn;
You are using SimpleDateFormat Incorrectly.
String pattern = "HH:mm" should be format in which your input Date String is. otherwise how is SimpleDateFormat going to know which portion represents what.
Create two SimpleDateFormat, f1 (with Input String Format) and f2 ( with output String Format) ;
Use f1.parse() to get Date object for Input String.
Then use f2.format() on this Date Object to get Output String representation.
Refer to SimpleDateFormat for details on how to specify date Format.
public static boolean currentTimeIsWithinStartAndEnd(String startTime,
String endTime) {
// assuming input date string is of format MM/dd/yyyy. Change it according to your needs.
String inputPattern = "MM/dd/yyyy";
String outputPattern = "HH:mm";
SimpleDateFormat inputFormatter = new SimpleDateFormat(inputPattern);
SimpleDateFormat outputFormatter = new SimpleDateFormat(outputPattern);
Date startTimeToCompare = inputFormatter.parse(startTime);
String dateInRequiredFormat = outputFormat.format(startTimeToCompare);

Converting Timestamp value in a prticular Date Time Format

I have a problem that I have a timestamp value which is coming from JSON parsing, I am converting that timastamp in Date Time Format which is desired, all is working fine but month always return 1 in any case. means If timestamp contains aug month but it returns only 1 for any month. I don't know how to resolve this. Please suggest me the solution for the same.
Thanks in advance.
Code:
public String create_datestring(String timestring){
try{
final Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(Long.parseLong(timestring));
timestring = String.valueOf(cal.get(Calendar.MONTH)+1) + "/" +String.valueOf(cal.get(Calendar.DAY_OF_MONTH)) + "/" + String.valueOf(cal.get(Calendar.YEAR));
}catch(NumberFormatException e){
timestring = "9/23/2011";--->timestring always returns 1 for month.
}
private String getDate(String timeStampStr){
try{
DateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
Date netDate = (new Date(Long.parseLong(timeStampStr)));
return sdf.format(netDate);
}
catch(Exception ex){
return dateInStr;
}
}
Try this one It may gives you satisfied output.
String DATE_FORMAT="hh:mm aa dd MMMM yyyy";
#SuppressLint("SimpleDateFormat")
private String getDate(long time) {
return new SimpleDateFormat(DATE_FORMAT).format(time * 1000);
}

Categories

Resources