Local time to EST time Conversion - android

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

Related

Convert UTC time in long value to GMT time in Android

I have UTC time in long value = 1555415100000L.
Now I want to convert to local time in different time zone.
example:
1555415100000L = 2019/04/16 18:45 (GMT+7)
1555415100000L = 2019/04/16 14:45 (GMT+3)
...
Do you have any suggestion to solve this problem?
I wrote this method. This method returns specific GMT as formatted String. You should give time in millisecond and GMT value to this method.
private String getSpecificGmtDate(long timeMillis, int gmt) {
long time = timeMillis + (gmt * 1000 * 60 * 60);
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
return (sdf.format(new Date(time)) + " (GMT " + gmt + ")");
}
output:
System.out.println(getSpecificGmtDate(1555415100000L, 0));
16/04/2019 11:45 (GMT 0)
System.out.println(getSpecificGmtDate(1555415100000L, 3));
16/04/2019 14:45 (GMT 3)
System.out.println(getSpecificGmtDate(1555415100000L, -3));
16/04/2019 08:45 (GMT -3)

How to convert number to hour and minute in 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

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

After Converting GMT time date not in 24hour format android code

I was trying to converted user inputed date in GMT time, user inputed date in 24hour format, when i convert in GMT time it show 12 hour problem, How can i get 24 hour formated GMT time
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String s = starttDatePicker.getYear() + "-"
+ (starttDatePicker.getMonth() + 1) + "-"
+ starttDatePicker.getDayOfMonth() + " "
+ starttimepicer.getCurrentHour() + ":"
+ starttimepicer.getCurrentMinute() + ":" + "00";
Date parsed = null;
try {
parsed = format1.parse(s);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
TimeZone tz = TimeZone.getTimeZone("GMT");
format1.setTimeZone(tz);
posttime = format1.format(parsed);
Change "yyyy-MM-dd hh:mm:ss" to "yyyy-MM-dd HH:mm:ss"
Just to clarify the documentation for formatting date/times mentions that hh is 12 hour time while HH is 24 hour time.
hh is for 12 hrs format and
HH is for 24 hrs format

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

Categories

Resources