codenameone convert time to utc - java

I am working on codename one project and I am struggling to convert device time to UTC.
I use this code :
Calendar cal = Calendar.getInstance();
System.out.println(cal.getTimeZone());
TimeZone tzUTC = TimeZone.getTimeZone("UTC");
com.codename1.l10n.DateFormat dtfmt = new com.codename1.l10n.SimpleDateFormat("EEE, yyyy-MM-dd KK:mm a z");
dtfmt.setTimeZone(tzUTC);
System.out.println("UTC: " + dtfmt.format(cal.getTime()));
and codename one reject the setTImeZone method.
I use java.text.DateFormat but when I run it, condename one cant compile it also.

It may not really answer your real question, but the following works for me:
Calendar cal = Calendar.getInstance();
DateFormat df = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.LONG);
TimeZone tzUtc = TimeZone.getTimeZone("UTC");
df.setTimeZone(tzUtc);
System.out.println("UTC: " + df.format(cal.getTime()));
I don’t know com.codename1.l10n.DateFormat, so I’m sorry I cannot help you there.

Use:
java.util.Calendar cal = java.util.Calendar.getInstance();
TimeZone tz = cal.getTimeZone();
cal.setTime(new Date(System.currentTimeMillis() - tz.getRawOffset()));
com.codename1.l10n.DateFormat dtfmt = new com.codename1.l10n.SimpleDateFormat("EEE, yyyy-MM-dd KK:mm a");
System.out.println("UTC: " + dtfmt.format(cal.getTime()));
Then append UTC to the string as the value is always UTC.

Was using Shai's solution but noticed that it wasn't giving the correct UTC time when the device timezone was in daylight savings time. Below is a more general solution using tz.getOffset() instead of tz.getRawOffset(). Seems like there should be simpler way!
L10NManager l10n = L10NManager.getInstance();
long sysRtnTime = System.currentTimeMillis() / 1000L;
Date errorDate = new Date(sysRtnTime * 1000L);
Date currentDate = new Date();
String deviceTime = l10n.formatDateTime(errorDate);
Calendar c = Calendar.getInstance();
long unixtime = errorDate.getTime();
TimeZone tz = c.getTimeZone();
// to get offset, we need era, year, month, day, dayOfWeek,millis
SimpleDateFormat yearFormat = new SimpleDateFormat("yyyy");
SimpleDateFormat monthDateFormat = new SimpleDateFormat("MM");
SimpleDateFormat dayDateFormat = new SimpleDateFormat("dd");
SimpleDateFormat dayOfWeekDateFormat = new SimpleDateFormat("F");
SimpleDateFormat millisDateFormat = new SimpleDateFormat("S");
int year = Integer.parseInt(yearFormat.format(currentDate));
int month = Integer.parseInt(monthDateFormat.format(currentDate));
int day = Integer.parseInt(dayDateFormat.format(currentDate));
int dayOfWeek = Integer.parseInt(dayOfWeekDateFormat.format(currentDate));
int millis = Integer.parseInt(millisDateFormat.format(currentDate));
// c.setTime(new Date(unixtime - tz.getRawOffset())); // c in UTC only if device not DST
month = month - 1; // since getOffset assume 0 = Jan and 11 = Dec
c.setTime(new Date(unixtime - tz.getOffset(1, year, month, day, dayOfWeek, millis))); // c in UTC (even if device in DST)
Date cDateUTC = c.getTime(); // sDate in UTC
String timeInUTC = serverDateFormat.format(cDateUTC);
Log.p("Time (in device timezone): " + deviceTime);
Log.p("Time (in UTC): " + timeInUTC);

Related

Get next day selected hour epoch

If the user selects 01:25 AM, how to get the corresponding epoch time for this hour for the next day?
I did something like that, which is pretty "face coded" :
private long returnEpochForThisHour(String hour){
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm");
Date date = new Date();
String stringDate = dateFormat.format(date).substring(0, 10) + " " + hour;
Date newDate = new Date(stringDate);
Calendar c = Calendar.getInstance();
c.setTime(newDate);
c.add(Calendar.DATE, 1);
Date lastDate = c.getTime();
System.out.println(lastDate.getTime());
return lastDate.getTime();
}
When doing something like:
returnEpochForThisTime("01:25");
It returns:
1544491500000
But in Android devices it's not working properly. Is there a better way to do this?

how to get years, months and days from date of birth in java [duplicate]

I have a Date object in Java stored as Java's Date type.
I also have a Gregorian Calendar created date. The gregorian calendar date has no parameters and therefore is an instance of today's date (and time?).
With the java date, I want to be able to get the year, month, day, hour, minute, and seconds from the java date type and compare the the gregoriancalendar date.
I saw that at the moment the Java date is stored as a long and the only methods available seem to just write the long as a formatted date string. Is there a way to access Year, month, day, etc?
I saw that the getYear(), getMonth(), etc. methods for Date class have been deprecated. I was wondering what's the best practice to use the Java Date instance I have with the GregorianCalendar date.
My end goal is to do a date calculation so that I can check that the Java date is within so many hours, minutes etc of today's date and time.
I'm still a newbie to Java and am getting a bit puzzled by this.
Use something like:
Date date; // your date
// Choose time zone in which you want to interpret your Date
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("Europe/Paris"));
cal.setTime(date);
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
// etc.
Beware, months start at 0, not 1.
Edit: Since Java 8 it's better to use java.time.LocalDate rather than java.util.Calendar. See this answer for how to do it.
With Java 8 and later, you can convert the Date object to a LocalDate object and then easily get the year, month and day.
Date date = new Date();
LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
int year = localDate.getYear();
int month = localDate.getMonthValue();
int day = localDate.getDayOfMonth();
Note that getMonthValue() returns an int value from 1 to 12.
Date date = new Date();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEEE");
System.out.println("DAY "+simpleDateFormat.format(date).toUpperCase());
simpleDateFormat = new SimpleDateFormat("MMMM");
System.out.println("MONTH "+simpleDateFormat.format(date).toUpperCase());
simpleDateFormat = new SimpleDateFormat("YYYY");
System.out.println("YEAR "+simpleDateFormat.format(date).toUpperCase());
EDIT: The output for date = Fri Jun 15 09:20:21 CEST 2018 is:
DAY FRIDAY
MONTH JUNE
YEAR 2018
You could do something like this, it will explain how the Date class works.
String currentDateString = "02/27/2012 17:00:00";
SimpleDateFormat sd = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date currentDate = sd.parse(currentDateString);
String yourDateString = "02/28/2012 15:00:00";
SimpleDateFormat yourDateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date yourDate = yourDateFormat.parse(yourDateString);
if (yourDate.after(currentDate)) {
System.out.println("After");
} else if(yourDate.equals(currentDate)) {
System.out.println("Same");
} else {
System.out.println("Before");
}
private boolean isSameDay(Date date1, Date date2) {
Calendar calendar1 = Calendar.getInstance();
calendar1.setTime(date1);
Calendar calendar2 = Calendar.getInstance();
calendar2.setTime(date2);
boolean sameYear = calendar1.get(Calendar.YEAR) == calendar2.get(Calendar.YEAR);
boolean sameMonth = calendar1.get(Calendar.MONTH) == calendar2.get(Calendar.MONTH);
boolean sameDay = calendar1.get(Calendar.DAY_OF_MONTH) == calendar2.get(Calendar.DAY_OF_MONTH);
return (sameDay && sameMonth && sameYear);
}
It might be easier
Date date1 = new Date("31-May-2017");
OR
java.sql.Date date1 = new java.sql.Date((new Date()).getTime());
SimpleDateFormat formatNowDay = new SimpleDateFormat("dd");
SimpleDateFormat formatNowMonth = new SimpleDateFormat("MM");
SimpleDateFormat formatNowYear = new SimpleDateFormat("YYYY");
String currentDay = formatNowDay.format(date1);
String currentMonth = formatNowMonth.format(date1);
String currentYear = formatNowYear.format(date1);
Date queueDate = new SimpleDateFormat("yyyy-MM-dd").parse(inputDtStr);
Calendar queueDateCal = Calendar.getInstance();
queueDateCal.setTime(queueDate);
if(queueDateCal.get(Calendar.DAY_OF_YEAR)==Calendar.getInstance().get(Calendar.DAY_OF_YEAR))
{
"same day of the year!";
}
#Test
public void testDate() throws ParseException {
long start = System.currentTimeMillis();
long round = 100000l;
for (int i = 0; i < round; i++) {
StringUtil.getYearMonthDay(new Date());
}
long mid = System.currentTimeMillis();
for (int i = 0; i < round; i++) {
StringUtil.getYearMonthDay2(new Date());
}
long end = System.currentTimeMillis();
System.out.println(mid - start);
System.out.println(end - mid);
}
public static Date getYearMonthDay(Date date) throws ParseException {
SimpleDateFormat f = new SimpleDateFormat("yyyyyMMdd");
String dateStr = f.format(date);
return f.parse(dateStr);
}
public static Date getYearMonthDay2(Date date) throws ParseException {
Calendar c = Calendar.getInstance();
c.setTime(date);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.HOUR_OF_DAY, 0);
return c.getTime();
}
public static int compare(Date today, Date future, Date past) {
Date today1 = StringUtil.getYearMonthDay2(today);
Date future1 = StringUtil.getYearMonthDay2(future);
Date past1 = StringUtil.getYearMonthDay2(past);
return today.compare // or today.after or today.before
}
getYearMonthDay2(the calendar solution) is ten times faster. Now you have yyyy MM dd 00 00 00, and then compare using date.compare

How to just change the TimeZone with SimpleDateFormat

I want to convert date from this format to Tue Sep 08 14:27:00 IST 2015 to 2015-09-08T14:27:00-0500 how to do this with SimpleDateFormat?
I tried like this way
Calendar cl = Calendar.getInstance();
SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
ft.setTimeZone(TimeZone.getTimeZone("US/Eastern"));
ft.format(cl.getTime());
the above code giving output 2015-09-08T04:57:00-0400 but I want to change only timezone and it should be -0500
How could I do this?
SimpleDateFormat uses a Calendar instance to work with Dates. If you change the timezone, the timezone of this Calendar instance is changed. If you really want to change only the output - in your case the timezone, without changing the Time (i do not know why you want to do this, but i assume you have a reason), you could do something like this:
Calendar cl = Calendar.getInstance();
TimeZone tz = TimeZone.getTimeZone("US/Eastern");//TimeZone.getDefault();
int offset = tz.getRawOffset();
String offsetStr = ((offset < 0) ? "-" : "+") + String.format("%02d%02d",
Math.abs(offset / 3600000), (offset / 60000) % 60);
SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'" + offsetStr+"'");
String dt = ft.format(cl.getTime());
use:
ft.setTimeZone(TimeZone.getTimeZone("GMT-5"))
sample:
Calendar cl = Calendar.getInstance();
SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
ft.setTimeZone(TimeZone.getTimeZone("US/Eastern"));
System.out.println(ft.format(cl.getTime()));
ft.setTimeZone(TimeZone.getTimeZone("GMT-5"));
System.out.println(ft.format(cl.getTime()));
produces:
2016-03-23T16:39:22-0400
2016-03-23T15:39:22-0500
source: https://docs.oracle.com/javase/6/docs/api/java/util/TimeZone.html
Below code is working fine for me
Calendar cl = Calendar.getInstance();
ZoneOffset offset = ZoneOffset.of(ZoneId.SHORT_IDS.get("EST"));
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'"+offset.getId()+"'");
formatter.format(cl.getTime());

Date to Unix timestamp

I have a string that looks like "2015-06-07 16:01:33.0". I want to convert it into a unix timestamp. First I use Calendar utility to convert it into a Date object. How can I convert the date to epoch time?
String origintime = "2015-06-07 16:01:33.0";
String year = origintime.split(" ")[0].split("-")[0];
String month = origintime.split(" ")[0].split("-")[1];
String day = origintime.split(" ")[0].split("-")[2];
String hour = origintime.split(" ")[1].split(":")[0];
String mins = origintime.split(" ")[1].split(":")[1];
String secs = origintime.split(" ")[1].split(":")[2].replace(".0","");
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, Integer.parseInt(day));
cal.set(Calendar.MONTH, Integer.parseInt(month));
cal.set(Calendar.YEAR, Integer.parseInt(year));
cal.set(Calendar.HOUR_OF_DAY,Integer.parseInt(hour));
cal.set(Calendar.MINUTE,Integer.parseInt(mins));
cal.set(Calendar.SECOND,Integer.parseInt(secs));
String strdate = null;
SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
if (cal != null) {
strdate = sdf.format(cal.getTime());
}
System.out.println(strdate);
I think you can search for answers at StackOverflow, instead of posting a new question, since it make StackOverflow better, I just did a quick search and here they are:
Getting unix timestamp from Date()
or here is the code that straight forward:
Date currentDate = new Date();
currentDate.getTime() / 1000;
Recently, people prefer jodaTime:
DateTime dateTime = new DateTime();
long unix = dateTime.getMillis()/1000;

Timestamp conversion in java

I am converting timestamp to date format yyyy-MM-dd HH:mm:ss.SSS and I am using America/New_York as TimeZone. Whenever I convert the timestamp into the date it shows one hour less than usual date and time. How to resolve this in java?
Here's the code:
String timestamp = "1431941838000";
long time = Long.valueOf(timestamp);
Date currentDate = new Date(time);
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
TimeZone zone = TimeZone.getTimeZone("America/New_York");
df.setTimeZone(zone);
String finale = df.format(currentDate);
Try to using EST to replace America/New_York like
TimeZone zone = TimeZone.getTimeZone("EST");
Updated
It's My Test code:
String timestamp = "1431941838000";
long time = Long.valueOf(timestamp);
Date currentDate = new Date(time);
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
TimeZone zoneNewYork = TimeZone.getTimeZone("America/New_York");
df.setTimeZone(zoneNewYork);
String finale = df.format(currentDate);
System.out.println(finale);
TimeZone zoneEst = TimeZone.getTimeZone("EST");
df.setTimeZone(zoneEst);
finale = df.format(currentDate);
System.out.println(finale);
And My result as bellow:
2015-05-18 05:37:18.000
2015-05-18 04:37:18.000
You have an extra point in this line:
TimeZone zone = TimeZone.getTimeZone("America/New_York").;
// ^ here!!!
UPDATE if you dont get any error, the output must be the correct:
EST is UTC - 5 hours. America/New_York is EST in the winter and E*D*T in the summer, so check if String timestamp = "1431941838000"; is winter or summer...
This code works ok:
Calendar calNewYork = Calendar.getInstance();
calNewYork.setTimeZone(TimeZone.getTimeZone("America/New_York"));
System.out.println("Time in New York: " + calNewYork.get(Calendar.HOUR_OF_DAY) + ":"
+ calNewYork.get(Calendar.MINUTE));
Use this to check your time:
long timestamp = "1431941838000";
Calendar calNewYork = Calendar.getInstance();
calNewYork.setTimeZone(TimeZone.getTimeZone("America/New_York"));
calNewYork.setTime(new Date(timestamp));
System.out.println("Time in New York: " + calNewYork.get(Calendar.HOUR_OF_DAY) + ":"
+ calNewYork.get(Calendar.MINUTE));

Categories

Resources