How to convert date and time to est format in android? - java

Here is my code.
public String getDateTime()
{
String dateAndTime =
(new SimpleDateFormat("hh:mm aaa")).format(new Date());
return dateAndTime;
}
public String getDate()
{
android.text.format.DateFormat df = new android.text.format.DateFormat();
String Date = df.format("MM-dd-yyyy", new java.util.Date()).toString();
return Date;
}
I have searched about this. but, i cant find the perfect answer. Please help me.

You can use the below function
private Date shiftTimeZone(Date date, TimeZone sourceTimeZone, TimeZone targetTimeZone) {
Calendar sourceCalendar = Calendar.getInstance();
sourceCalendar.setTime(date);
sourceCalendar.setTimeZone(sourceTimeZone);
Calendar targetCalendar = Calendar.getInstance();
for (int field : new int[] {Calendar.YEAR, Calendar.MONTH, Calendar.DAY_OF_MONTH, Calendar.HOUR, Calendar.MINUTE, Calendar.SECOND, Calendar.MILLISECOND}) {
targetCalendar.set(field, sourceCalendar.get(field));
}
targetCalendar.setTimeZone(targetTimeZone);
System.out.println("........"+targetCalendar.getTimeZone());
return targetCalendar.getTime();
}
Usage:
Date date= new Date();
SimpleDateFormat sf = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
sf.format(date);
TimeZone tz = TimeZone.getTimeZone("GMT") OR TimeZone tz = sf.getTimeZone();
TimeZone tz1 = TimeZone.getTimeZone("EST");
Date c= shiftTimeZone( date,tz,tz1);
System.out.println("Format : " + sf.format(c));
Output
sun.util.calendar.ZoneInfo[id="EST",offset=-18000000,dstSavings=0,useDaylight=false,transitions=0,lastRule=null]
Format : 01-05-2013 16:23:57

You can find your answer here :
Date and time conversion to some other Timezone in java
You have to use TimeZone class and Calendar class.
Get current time :
Calendar currentdatetime = Calendar.getInstance();
Just pass your time zone name in TimeZone class like this :
TimeZone.getTimeZone("EST");
Use DateFormater
DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
Then format your time like this :
formatter.setTimeZone(obj);
and get output like this :
System.out.println("EST Time is : "+ formatter.format(currentdatetime .getTime())

Related

JAVA gives me wrong Date Results on Several devices

I have a weird problem I used Java to get a current date but I am getting different results on several devices, on one correct & on another wrong.
Here is my code:
public String getCurrentDate() {
/// get date
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);
dateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Tehran"));
Date date = new Date();
System.out.println(dateFormat.format(date)); //2017-11-13 18:20:46 correct time is 11am
return dateFormat.format(date);
}
On the device that gives the wrong result I set automatic time zone use network-provided time zone & time of the device is correct.
Are testing with real devices?
You can also try the Calendar Class that are from Android. for more info visit (https://developer.android.com/reference/java/util/Calendar.html)
Check the Example bellow:
Calendar current_time_cal = Calendar.getInstance();
current_time_cal.setTimeZone(TimeZone.getTimeZone("Asia/Tehran"));
int hours = current_time.get(Calendar.HOUR);
int current_am_pm = current_time.get(Calendar.AM_PM);
current_time_cal.set(Calendar.HOUR_OF_DAY, (hours == 0)? 12 : hours);
current_time_cal.set(Calendar.MINUTE, current_time.get(Calendar.MINUTE));
current_time_cal.set(Calendar.SECOND, 0);
Try this:
Calendar c = Calendar.getInstance();
System.out.println("Current time: " + c.getTime());
SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy");
String formattedDate = df.format(c.getTime());
You can use this method to get current time from your device:
public String getCurrentDate() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar calendar = Calendar.getInstance();
String date = sdf.format(calendar.getTime());
return date;
}
This method will return current date as string.

How to Convert Time Zone to UTC time zone using jorda time

Using this code
String twelveHourTime="06:00 PM";
public static DateTime convert12HourTimeTo24HourTime(String twelveHourTime) {
DateTimeFormatter dateTimeFormatter =
DateTimeFormat.forPattern(AppConstants.TWELVE_HOUR_TIME_FORMAT);
DateTime dateTime = dateTimeFormatter.parseDateTime(twelveHourTime);
return new DateTime().withHourOfDay(dateTime.getHourOfDay())
.withMinuteOfHour(dateTime.getMinuteOfHour());
}
I am getting this date time:
String datetime=2017-09-15T18:00:23.153+05:30
Now I want to convert it to the US time zone.
Please suggest me how to do this.
You can use SimpleDateFormat for conversion
DateFormat df = new SimpleDateFormat("dd/MM/yyyy HH24:MI");
Date date = df.parse(datetime);
Use localDateTime:
DateTime dt = new LocalDateTime(timestamp.getTime()).toDateTime(DateTimeZone.UTC);
you can use it by using TimeZone and SimpleDateFormat :-
TimeZone time = TimeZone.getTimeZone("UTC");
Calendar cal = Calendar.getInstance(time);
final Date startDate = cal.getTime();
SimpleDateFormat sdfAmerica = new SimpleDateFormat("dd-M-yyyy hh:mm:ss a");
sdfAmerica.setTimeZone(TimeZone.getTimeZone("America/New_York"));
String sDateInAmerica = sdfAmerica.format(startDate);
edDate.setText(sDateInAmerica);

issue with comparing two dates in joda time API

I have a below program to compare two dates.
I get timestamps that are date1 and currentTimestamp, here i need to compare only dates not the time values.But below program always returns -1.(value)
timestamp date1 = "2017-01-20 14:51:30.091" // i get this from service call in this format
SimpleDateFormat dateFormat = new SimpleDateFormat(DEFAULT_TIMESTAMP_FORMAT);
Calendar calendar = Calendar.getInstance();
String formattedDate = dateFormat.format(calendar.getTime());
java.util.Date currentDate = dateFormat.parse(formattedDate);
java.sql.Timestamp currentTimestamp = new java.sql.Timestamp(currentDate.getTime());
int value = DateTimeComparator.getDateOnlyInstance().compare(date1 , currentTimestamp );
How to compare only dates regardless of time. Please help me on this.
UPDATED:
i changed to below code
timestamp date1 = "2017-01-20 14:51:30.091" // i get this from service call in this format
LocalDate localDate = new LocalDate();
int value = DateTimeComparator.getDateOnlyInstance().compare(date1 , localDate );
this gives me error saying "java.lang.IllegalArgumentException: No instant converter found for type: org.joda.time.LocalDate"
This is NOT Joda solution...
Use: Apache library 'commons-lang3-x.x.jar' (DateUtils)
#Test
public void testCompare() {
Date current = new Date();
Date previous = DateUtils.addHours(DateUtils.addDays(new Date(), -1),5);
assertEquals(1,DateUtils.truncatedCompareTo(current,previous,Calendar.DATE));
assertEquals(0,DateUtils.truncatedCompareTo(current,current,Calendar.DATE));
assertEquals(-1,DateUtils.truncatedCompareTo(previous,current,Calendar.DATE));
}
You can Try this code with JodaTime :
DateTime date1 = DateTime.parse("2017-01-20 14:51:30.091", DateTimeFormat.forPattern("YYYY-MM-dd HH:mm:ss.SSS"));
DateTime now = new DateTime();
int value = DateTimeComparator.getDateOnlyInstance().compare(date1 , now);
To compare DateTime in joda without time you have 2 options:
convert DateTime to LocalDate .
Use DateTimeComparator.getDateOnlyInstance
For example:
#Test
public void compareJodaTime() {
DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSS");
String today = "2017-01-20 14:51:30.091";
String tomorrow = "2017-01-21 14:51:30.091";
DateTime now = DateTime.now();
Assert.assertThat(now.toLocalDate().compareTo(DateTime.parse(today, dateTimeFormatter).toLocalDate()), Matchers.is(0));
Assert.assertThat(now.toLocalDate().compareTo(DateTime.parse(tomorrow, dateTimeFormatter).toLocalDate()), Matchers.is(-1));
Assert.assertThat(now.toLocalDate().isEqual(DateTime.parse(today, dateTimeFormatter).toLocalDate()), Matchers.is(true));
Assert.assertThat(now.toLocalDate().isBefore(DateTime.parse(tomorrow, dateTimeFormatter).toLocalDate()), Matchers.is(true));
Assert.assertThat(DateTimeComparator.getDateOnlyInstance().compare(now, DateTime.parse(today, dateTimeFormatter)), Matchers.is(0));
Assert.assertThat(DateTimeComparator.getDateOnlyInstance().compare(now, DateTime.parse(tomorrow, dateTimeFormatter)), Matchers.is(-1));
}

Java convert UTC timestamp to local DateTime

I know there are dozens of answered posts about converting UTC Time/Date To/From local time already but non helped me to figure out what my problem is.
My question is:
By having UTC timestamp, how can i get local DateTime?
This is what I have right now but this just convert the timestamp to DateTime format.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getDefault());
sdf.format(new Date(timestamp * 1000));
Edited: I'm saving the UTC timestamp on the cloud so every device (Android/iOS) can query and convert to it's time zone.
Try this is working with me
public String getDateCurrentTimeZone(long timestamp) {
try{
Calendar calendar = Calendar.getInstance();
TimeZone tz = TimeZone.getDefault();
calendar.setTimeInMillis(timestamp * 1000);
calendar.add(Calendar.MILLISECOND, tz.getOffset(calendar.getTimeInMillis()));
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date currenTimeZone = (Date) calendar.getTime();
return sdf.format(currenTimeZone);
}catch (Exception e) {
}
return "";
}
You can try this
String DATE_FORMAT = "EEE, dd MMM yyyy HH:mm:ss a z" ;
final SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
String dateTimeString = sdf.format(new Date());
System.out.println(dateTimeString); // current UTC time
long timeStamp=sdf.parse(dateTimeString).getTime(); //current UTC time in milisec
Calendar cal = Calendar.getInstance();
cal.setTime(new Date(timeStamp));
cal.add(Calendar.HOUR_OF_DAY, 5);
cal.add(Calendar.MINUTE, 30);
System.out.println(sdf.format(cal.getTime())); // time relevant to UTC+5.30
U can use Joda time to convert local to UTC and vice-versa
e.g Local to UTC
DateTime dateTimeNew = new DateTime(date.getTime(), DateTimeZone.forID("Asia/Calcutta"));
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
String datetimeString = dateTimeNew.toString("yyyy-MM-dd HH:mm:ss");
long milis = 0;
try {
milis = simpleDateFormat.parse(datetimeString).getTime();
} catch (ParseException e) {
e.printStackTrace();
}

How to get full date in android?

I know about to get the date in android with the help of the calender instance.
Calendar c = Calendar.getInstance();
System.out.println("====================Date is:"+ c.get(Calendar.DATE));
But with that i got only the number of the Date. . .
In My Application i have to do Some Calculation based on the Date Formate. Thus if the months get changed then that calculation will be getting wrong.
So for that reason i want the full date that gives the Month, Year and the date of the current date.
And what should be done if i want to do Some Calculation based on that date ?
As like: if the date is less then two weeks then the message should be printed. . .
Please Guide me in this.
Thanks.
Look at here,
Date cal=Calendar.getInstance().getTime();
String date = SimpleDateFormat.getDateInstance().format(cal);
for full date format look SimpleDateFormat
and IF you want to do calculation on date instance I think you should use, Calendar.getTimeInMillis() field on these milliseconds make calculation.
EDIT: these are the formats by SImpleDateFormat class.
String[] formats = new String[] {
"yyyy-MM-dd",
"yyyy-MM-dd HH:mm",
"yyyy-MM-dd HH:mmZ",
"yyyy-MM-dd HH:mm:ss.SSSZ",
"yyyy-MM-dd'T'HH:mm:ss.SSSZ",
};
for (String format : formats) {
SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.US);
System.err.format("%30s %s\n", format, sdf.format(new Date(0)));
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
System.err.format("%30s %s\n", format, sdf.format(new Date(0)));
}
EDIT: two date difference (Edited on Date:09/21/2011)
String startTime = "2011-09-19 15:00:23"; // this is your date to compare with current date
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date1 = dateFormat.parse(startTime);
// here I make the changes.... now Date d use a calendar's date
Date d = Calendar.getInstance().getTime(); // here you can use calendar beco'z date is now deprecated ..
String systemTime =(String) DateFormat.format("yyyy-MM-dd HH:mm:ss", d.getTime());
SimpleDateFormat df1;
long diff = (d.getTime() - date1.getTime()) / (1000);
int Totalmin =(int) diff / 60;
int hours= Totalmin/60;
int day= hours/24;
int min = Totalmin % 60;
int second =(int) diff % 60;
if(day < 14)
{
// your stuff here ...
Log.e("The day is within two weeks");
}
else
{
Log.e("The day is more then two weeks");
}
Thanks.
Use SimpleDateFormat class,
String date = SimpleDateFormat.getDateInstance().format(new Date());
you can use
//try different flags for the last parameter
DateUtils.formatDateTime(context,System.currentTimeMillis(),DateUtils.FORMAT_SHOW_DATE);
for all options check http://developer.android.com/reference/android/text/format/DateUtils.html
try this,
int month = c.get(Calendar.MONTH);
int year = c.get(Calendar.YEAR);
int day = c.get(Calendar.DAY_OF_MONTH);
System.out.println("Current date : "
+ day + "/" + (month + 1) + "/" + year);
}
I'm using following methods to get date and time. You can change the locale here to arabic or wot ever u wish to get date in specific language.
public static String getDate(){
String strDate;
Locale locale = Locale.US;
Date date = new Date();
strDate = DateFormat.getDateInstance(DateFormat.DEFAULT, locale).format(date);
return strDate;
}
public static String getTime(){
String strTime;
Locale locale = Locale.US;
Date date = new Date();
strTime = DateFormat.getTimeInstance(DateFormat.DEFAULT, locale).format(date);
return strTime;
}
you can get the value and save it on String as below
String Date= getDate();
String Time = getTime();

Categories