Get next day selected hour epoch - java

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?

Related

How to get perfect UTC Time in java/android?

I am trying to get UTC time in my application but unfortunately every time I am getting my current emulator Date and Time Instead of UTC.
Tried,
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
ZonedDateTime utcTime = ZonedDateTime.now(ZoneOffset.UTC);
DateTime now = DateTime.now(DateTimeZone.UTC);
My code:
//create UTC time
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
System.out.println("DATETIME ==> " + cal.getTime());
ZonedDateTime utcTime = ZonedDateTime.now(ZoneOffset.UTC);
System.out.println("DATETIME = " + utcTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
DateTime now = DateTime.now(DateTimeZone.UTC);
System.out.println("DATETIME = " + now);
Any help highly appreciated.
Try this code:
private String getCurrentDateTimeAccordingToUTC(String format) {
Date date = new Date(System.currentTimeMillis());
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
return simpleDateFormat.format(date);
}
String date = getCurrentDateTimeAccordingToUTC("dd-MM-yyyy hh:mm:ss a");
Log.e("date--","inUTC--:"+date);

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

codenameone convert time to utc

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

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;

How to display last six dates, java.util.Date?

I went to display the current date and the six (6) last dates
example :
02/11/2012
01/11/2012
31/10/2012
30/10/2012
29/10/2012
28/10/2012
to get the current day in JAVA I used :
Date date = Calendar.getInstance().getTime();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
System.out.println("current day : "+sdf.format(date));
but how do I decrement the days ?
You can use the Calendar#add method to substract a day, like:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
Calendar cal = Calendar.getInstance();
Date date=cal.getTime();
System.out.println(sdf.format(date)); //remove line to display only the last 5 days
for (int i=0;i<5;i++){
cal.add(Calendar.DAY_OF_MONTH,-1);
date=cal.getTime();
System.out.println(sdf.format(date));
}
Like Jon Skeet (soon Mr. 500k :) ) suggested, I too find the Joda Time API more cleaner and appropriate, even for such simple tasks:
DateTime dt = new DateTime();
for (int i = 0; i < 6; i++) {
System.out.println(dt.toString("yyyy/MM/dd"));
dt = dt.minusDays(1);
}
Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
System.out.println("current day : "+sdf.format(c.getTime()));
// decrement 1 day
c.add(Calendar.DAY_OF_MONTH, -1);
// getTime() returns a java.util.Date
System.out.println("the day before : "+sdf.format(c.getTime()));
// getTimeInMillis() returns a long, which can be used to construct a java.sql.Date
System.out.println("the day before : "+sdf.format(new java.sql.Date(c.getTimeInMillis()));
And so on...

Categories

Resources