I need to convert date and time in hex code for writing it on IOT device.
Here is my code
private String getDateTimeToHexa() {
Calendar mCalendar = Calendar.getInstance();
TimeZone gmtTime = TimeZone.getTimeZone(TimeZone.getDefault().getDisplayName());
mCalendar.setTimeZone(gmtTime);
final Date date = mCalendar.getTime();
return Long.toHexString(date.getTime());
}
It is returning 11 digits hex code I need 8 digits, just like date and time in hex is 47C7EDE0 for this date 12:34:56 29/Feb/2008
Please help
import java.util.Calendar;
import java.util.Date;
public class Date {
public static void main(final String[] args)
{
final Calendar cal = Calendar.getInstance();
cal.set(Calendar.DATE, 15);
cal.set(Calendar.MONTH, Calendar.DECEMBER);
cal.set(Calendar.YEAR, 2005);
cal.set(Calendar.HOUR, 17);
cal.set(Calendar.MINUTE, 35);
cal.set(Calendar.SECOND, 20);
final Date date = cal.getTime();
System.out.printf("Date %s is encoded as: %s\n", date, Long.toHexString(date.getTime()));
// decode with: new Date(Long.parseLong("1082f469308", 16))
}
}
Try this:
private String getDateTimeToHexa() {
Calendar mCalendar = Calendar.getInstance();
TimeZone gmtTime = TimeZone.getTimeZone(TimeZone.getDefault().getDisplayName());
mCalendar.setTimeZone(gmtTime);
final Date date = mCalendar.getTime();
return Long.toHexString(date.getTime()/1000);
}
Instead of returning
return Long.toHexString(date.getTime());
Return following
return Long.toHexString(date.getTime()/1000);
As correctly pointed out by #shmosel that date.getTime() return time in a millisecond and if you want 8 digit Hex format then it needs to be converted in the second format.
The return type of Date can be found here
Related
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
Where is some function to get the last day of month in my service?
DateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
Date date = format.parse(stringDate);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.MONTH, 1);
calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar.add(Calendar.DATE, -1);
Date lastDayOfMonth = calendar.getTime();
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
return sdf.format(lastDayOfMonth);
So, this method correctly works elsewhere, but in US last day is always 29 (last day - 1)
stringDate is date in format "yyyy-MM-dd"
I believe this problem is due to Day Light saving time in US.
You can change this by setting the Timezone for Calendar to different timezone.
Related question: Adding days with java.util.Calendar gives strange results
Java Date has very poor API. Instead of this I would recommend you to use Joda Time.
In Joda it would look like this:
LocalDate endOfMonth = date.dayOfMonth().withMaximumValue();
If you don't have Java 8, this is very compact with JodaTime.
import org.joda.time.DateTime;
public class SoLastDay {
public DateTime lastDay(final String yyyy_MM_dd) {
DateTime givenDate = new DateTime(yyyy_MM_dd);
return givenDate.dayOfMonth().withMaximumValue();
}
}
And a small test...
#Test
public void testLastDay() throws Exception {
SoLastDay soLastDay = new SoLastDay();
String date1 = "2015-01-27";
System.out.printf("Date %s becomes %s.\n", date1, soLastDay.lastDay(date1).toString("yyyy-MM-dd"));
String date2 = "2015-02-02";
System.out.printf("Date %s becomes %s.\n", date2, soLastDay.lastDay(date2).toString("yyyy-MM-dd"));
}
And the test results:
Date 2015-01-27 becomes 2015-01-31.
Date 2015-02-02 becomes 2015-02-28.
If you do have Java 8, you might use code like this:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
public class SoLastDayJava8 {
static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
public LocalDate lastDay(final String yyyy_MM_dd) {
LocalDate givenDate = LocalDate.parse(yyyy_MM_dd, formatter);
return givenDate.with(TemporalAdjusters.lastDayOfMonth());
}
}
The test code changes just a bit.
public class SoLastDayJava8Test {
#Test
public void testLastDay() throws Exception {
SoLastDayJava8 soLastDay = new SoLastDayJava8();
String date1 = "2015-01-27";
System.out.printf("Date %s becomes %s.\n", date1, soLastDay.lastDay(date1));
String date2 = "2015-02-02";
System.out.printf("Date %s becomes %s.\n", date2, soLastDay.lastDay(date2));
}
}
But the results are the same.
Date 2015-01-27 becomes 2015-01-31.
Date 2015-02-02 becomes 2015-02-28.
You are messing with the TimeZones.
When you execute Date date = format.parse(stringDate); you are creating a Date object with the TimeZone of the DateFormat object. Theoretically if the TimeZone is the same for all your DateFormat and Calendar objects, you should be fine. Check if they are coherent with the getTimeZone() method.
If the TimeZone of the first DateFormat is wrong (e.g. is your TimeZone or UTC or GMT), you'll get a UTC-008 conversion in the second TimeZone (and in the Calendar) resulting in the missing day since you start from midnight.
Judging from your code is the stringDate itself that has been wrongly converted somewhere else...
import java.util.GregorianCalendar;
public class CalendarMain {
public static void main(String[] args) {
GregorianCalendar calendar = new GregorianCalendar();
int month = calendar.get(GregorianCalendar.MONTH)+1;
int year = calendar.get(GregorianCalendar.YEAR);
int weekday = calendar.get(GregorianCalendar.DAY_OF_WEEK);
int dayOfMonth = calendar.get(GregorianCalendar.DAY_OF_MONTH);
System.out.println(month+"/"+dayOfMonth+"/"+year);
calendar.add(GregorianCalendar.DAY_OF_MONTH, 10);
System.out.println(GregorianCalendar.DAY_OF_MONTH);
}
}
I am trying to add 10 days to the current date but am getting a weird problem. It does not seem to be adding correctly.
Output:
9/18/2014
5
// Get a calendar which is set to a specified date.
Calendar calendar = new GregorianCalendar(2014, Calendar.JANUARY, 1);
// Get the current date representation of the calendar.
Date startDate = calendar.getTime();
// Increment the calendar's date by 1 day.
calendar.add(Calendar.DAY_OF_MONTH, 1);
// Get the current date representation of the calendar.
Date endDate = calendar.getTime();
System.out.println(startDate);
System.out.println(endDate);
I think the last row is wrong, try this:
System.out.println(calendar.get(GregorianCalendar.DAY_OF_MONTH));
Use
System.out.println(calendar.get(GregorianCalendar.DAY_OF_MONTH));
instead of
System.out.println(GregorianCalendar.DAY_OF_MONTH);
Output :
9/18/2014
28
What you were doing in your code is printing the integer code of GregorianCalendar.DAY_OF_MONTH final variable, Which will remain 5, no matter what you have added in calendar. You were needed to use calendar.get(...) function to get the date of month of this calendar.
How can I verify if the calculated date is correct through selenium web driver?
Consider the following examples below:
From Date: 01/01/2001
Duration: 10
To Date: 01/10/2001
I will instruct selenium to input a date on from date field and duration.
The system shall automatically calculates the To date based on the inputted from date and duration.
I wonder if there's a way to verify if the calculated To Date is correct given that the inputted values on from date and duration fields may change time to time.
Static values for from date and duration fields is okay too - I guess.
Thanks!
You can do this using java.util methods. I assume you will be pass From Date and Duration as string to your selenium/webdriver from your test data set. You have to do following for each test data:
Calculate the To Date using util method (Code below for getToDate).
Get text in To Date using selenium/webdriver, for your test data.
Compare the text fetched by selenium/webdriver with the text returned by your getToDate method.
The method to get To Date:
public static String getToDate(String fromDate, String duration){
try {
String[] arrFromDate = fromDate.split("/");
int fromMonth = Integer.parseInt(arrFromDate[0])-1;
int fromDay = Integer.parseInt(arrFromDate[1]);
int fromYear = Integer.parseInt(arrFromDate[2]);
int intDuration = Integer.parseInt(duration);
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, fromDay);
cal.set(Calendar.MONTH, fromMonth);
cal.set(Calendar.YEAR, fromYear);
cal.add(Calendar.DAY_OF_MONTH, intDuration);
String toDate = sdf.format(cal.getTime());
return toDate;
} catch (NumberFormatException e) {
e.printStackTrace();
return null;
}
Code to verify:
String appToDate = driver.findElement(By.id("toDate")).getText();
String myToDate = getToDate("01/01/2001","10");
boolean isToDateCorrect = false;
if (appToDate.equals(myToDate )){
isToDateCorrect = true;
}
I suggest parsing the date instead of splitting the string
String strDate = "01/01/2001";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy");
Date date = simpleDateFormat.parse(strDate);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DATE, 10); // 10 == duration
String outStr = simpleDateFormat.format(calendar.getTime());
This question already has answers here:
How can I increment a date by one day in Java?
(32 answers)
How to subtract X day from a Date object in Java?
(10 answers)
Closed 8 years ago.
Can any one help me with the code for adding some number of days to any date..?
For example today is 11-04-2014. I want 15-04-2014 + 3 days output:18-04-2014.
My question is not adding dates to current date..
With Java 8, you can write:
import java.time.LocalDate;
LocalDate date = LocalDate.of(2014, 4, 11);
LocalDate newDate = date.plusDays(3);
System.out.println(newDate); // Prints 2014-04-14
Its that simple.
String dateString = "11-04-2014" // Say you have a date in String format
SimpleDateFormat format = new SimpleDateFormat("MM-dd-yyyy"); // Create an instance of SimpleDateFormat with the right format.
Date date = format.parse(dateString); // Then parse the string, this will need a try catch statement.
Calendar calendar = Calendar.getInstance(); // Get an instance of the calendar.
calendar.setTime(date); // Set the time of the calendar to the parsed date
calendar.add(Calendar.DATE, 3); // Add the days to the calendar
String outputFormat = format.format(calendar.getTime());
import java.util.Calendar;
import java.text.SimpleDateFormat;
public class A {
public static void main(String[] args) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy");
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar.set(Calendar.MONTH, 1);
calendar.set(Calendar.YEAR, 2012);
calendar.add(Calendar.DAY_OF_MONTH, 3);
System.out.println(simpleDateFormat.format(calendar.getTime()));
}
}
You can use the calendar function:
Calendar cal = Calendar.getInstance();
cal.setTime(dateInstance);
cal.add(Calendar.DATE, NO_OF_DAYS_TO_ADD);
Date addedDays = cal.getTime();
DateInstance is the date you are using. addedDays can be formatted using SimpleDateFormat to display in any date format that you would like to use.