Convert Excel timestamp to java.sql.date - java

I am extracting a timestamp out of Excel (2010):
It is displayed as "10.06.2015 14:24". The "internal representation" of excel is "42165.6". Last one is outputted from Excel.
So, for now, I want to parse this timestamp into a Java program like this:
double input = 42165.6;
// long myLong = ???
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm");
System.out.println(sdf.format(new java.sql.Date(myLong)));
How can I do this in line 2?!
Many thanks for your help!!!
Kind regards

Excel stores dates as the number of days since January 1900. This makes it awkward to convert into a Java date (milliseconds since 1 Jan 1970). If you cannot export it in a readable format, you'll need to create a Java Calendar, set it to 1 Jan 1900, and add the number of days.
Here it is:
double excelDate = 42165.6;
int days = (int) excelDate; //number of days
int seconds = (int) ((excelDate-days) * 86400); //number of seconds in .6 days
//create calendar set to 01-Jan-1900
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, 1900);
cal.set(Calendar.MONTH, 0);
cal.set(Calendar.DAY_OF_MONTH, 1);
//Add days and seconds to get required date/time
cal.add(Calendar.DATE, days-1);
cal.add(Calendar.SECOND, seconds);
//cal.getTime() returns a java.util.Date, print it out...
System.out.println(cal.getTime());
NOTE
A java.sql.Date can be created from a java.util.Date as follows:
java.util.Date utilDate = ....
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());

The fastest way to get from the excel notation to a java.sql.Date is:
double excelInput = 42165.6;
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm");
System.out.println("---> "
+ sdf.format(new java.sql.Date(
(long) ((excelInput - 25569) * 86400 * 1000))));
Excel stores a date since 01-01-1900, java.sql.date since 01-01-1970. There are exactly 25569 days difference between both dates. The constructor of java.sql.Date wants the milliseconds (!) since 01-01-1970, so with "* 86400" we get the seconds and then with (* 1000) the milliseconds.
That's it! ;)

Putting 42165.6 in excel and formatting to a date gives the correct date 6/10/15 14:24.
For me the answers by mrbela and NickJ both gave incorrect answers to the question of 42165.6, 06/10/2015 09:23 and 06/12/2015 03:25. This seems to be true of most of the examples I've tried.
The solution that worked for me was to use Apache POI, which is a java API for Microsoft Documents. This question is very similar and had the pointers that led me to poi.
Here is a working code example.
double input = 42165.6;
Date date = DateUtil.getJavaDate(input);
System.out.println(new SimpleDateFormat("dd.MM.yyyy HH:mm").format(javaDate));
which outputs the correct 06/10/2015 14:24

Related

Java get current day from unix timestamp [duplicate]

This question already has answers here:
Java: Date from unix timestamp
(11 answers)
Closed 5 years ago.
I want to convert unix timestamp to only the current day, like the current day of the month of current day of the year, is it possible to do only using math, like *, /, or something?
The short solution is something like
long epoch = 1501350790; // current unix time
int day = Integer.parseInt(new SimpleDateFormat("dd").format(new Date(epoch * 1000L)));
it is possible to get this result by calculation (* and /) but there is no easy way. you can use the implementation of java.util.GregorianCalendar as reference
You can use SimpleDateFormat to format your date:
long unixSeconds = 1372339860;
Date date = new Date(unixSeconds*1000L); // *1000 is to convert seconds to milliseconds
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z"); // the format of your date
sdf.setTimeZone(TimeZone.getTimeZone("GMT-4")); // give a timezone reference for formating (see comment at the bottom
String formattedDate = sdf.format(date);
System.out.println(formattedDate);
You can also convert it to milliseconds by multiplying the timestamp by 1000:
java.util.Date dateTime=new java.util.Date((long)timeStamp*1000);
After doing it, you can get what you want:
Calendar cal = Calendar.getInstance();
cal.setTime(dateTime);
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH); //here is what you need
int day = cal.get(Calendar.DAY_OF_MONTH);
You can calculate the date from a unix timestamp with java.util.Date
You need to multiply the timestamp with 1000, because java expects milliseconds. You can use the cal.get(Calendar.DAY_OF_MONTH) function to print the day.
import java.sql.Timestamp;
import java.util.Calendar;
public class MyFirstJavaProgram {
public static void main(String []args) {
long unixTimeStamp= System.currentTimeMillis() / 1000L;
java.util.Date time=new java.util.Date((long)unixTimeStamp*1000);
Calendar cal = Calendar.getInstance();
// It's a good point better use cal because date-functions are deprecated
cal.setTime(time);
System.out.println(cal.get(Calendar.DAY_OF_MONTH));
}
}
Any further questions please leave a comment.

Subtracting two dates in Java

I want to subtract two dates (one constant and one current) in Java but I've got strange problems with it. Here is the code :
DateFormat df = new SimpleDateFormat("HH:MM");
Date FirstLessonInterval=df.parse("08:45");
Date currentTime = new Date();
long diff = FirstLessonInterval.getTime()-currentTime.getTime();
String s = String.valueOf(diff);
LessonOrBreak=(diff);
I've got minus minutes. When I want to see FirstLessonInterval with FirstLessonInterval.toString() it shows the year 1970. What can I do?
You forgot to give a date, you just defined a time:
DateFormat df = new SimpleDateFormat("HH:MM");
Date FirstLessonInterval=df.parse("08:45");
and this is in unix time day 0 which is the 1.1.1970
try something like
DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:MM");
Date FirstLessonInterval=df.parse("2014/05/10 08:45");
1970 is where all time began according to computers. Are we missing some code in your question? You can faff around with the current time in milliseconds but i'd take a look at JodaTime and use that.
The reason you are getting 1970.... is because I suspect your diff is quite a small number. Then if you look at that as a date then it will be a small number + 1 Jan 1970 which will still be in 1970. But as i said I suspect we are missing some code in your question.
In JodaTime you can do somethign like the below but im not sure what it is you are exactly after
Interval i= new Interval(new DateTime(FirstLessonInterval), new DateTime());
System.out.println("Interval is: " + i.toDurationMillis());
Your format pattern is incorrect, use lower case mm to represent minutes
When you do not specify much details to the outdated Java date api, it considers the time since UNIX epoch (1st Jan 1970)
Since you are assuming the date to be the same as the constant time parameters you provide and independent of the timezones, you can bring your current date comparable to the time since UNIX epoch:
Staying close to your original code;
DateFormat df = new SimpleDateFormat("HH:mm");
Date firstLessonInterval = df.parse("08:45");
Date currentTime = new Date();
// Format the current date comparable to UNIX epoch (only hold time params)
String dateStr = df.format(currentTime.getTime());
// Parse the modified date string to a date object
Date comDate = df.parse(dateStr);
// Take the difference in millis
long diff = firstLessonInterval.getTime() - comDate.getTime();
String s = String.valueOf(diff);
// Print the number of minutes passed since
System.out.println("Minutes {elapsed since/time to} 08:45 - " + Math.abs(diff) / 1000 / 60);
Missing Date Portion
As the other correct answers said, you are using the java.util.Date class which is a date-time class holding both a date portion and a time portion.
LocalTime
If you truly care about only time of day, with no date and no time zone, then use the LocalTime class found in both the Joda-Time library and the new java.tome package in Java 8. By the way the old java.util.Date and .Calendar classes are notoriously troublesome and should be avoided.
Joda-Time
Here is some code with date-time and time zone.
Using the Joda-Time 2.3 library…
DateTimeZone timeZone = DateTimeZone.forID( "Europe/Warsaw" );
DateTime dateTime = new DateTime( 2014, 1, 2, 8, 45, 0, timeZone );
DateTime now = new DateTime( 2014, 1, 2, 8, 30, 0, timeZone ); // Or DateTime.now( timeZone )
Duration duration = new Duration( dateTime, now ); // or use Period or Interval.
Joda-Time offers intelligent classes and methods of working with a span of time (a Period, Interval, or Duration). For example look at the Minutes class. But if all you need is millseconds, here you go.
long millis = duration.getMillis();
The problem is that you are not providing enough info to SimpleDateFormat. It sets the hour and minutes correctly but nothing else.
DateFormat df = new SimpleDateFormat("HH:mm");
System.out.println(df.parse("08:45")); // Thu Jan 01 08:45:00 GMT 1970
System.out.println(new Date()); // Sun May 11 07:52:50 GMT 2014
If you want your date to be with respect to the current date try this:
Date curr = new Date();
Date date = new Date(curr.getYear(),
curr.getMonth(),
curr.getDate(),
8, 45, 0);
System.out.println(date); // Sun May 11 08:45:00 GMT 2014
System.out.println(curr); // Sun May 11 07:52:50 GMT 2014
long diff = date.getTime() - curr.getTime();
System.out.println("Minutes: " + diff/6000); // Minutes: 53
I dont know if this way is efficient or not but it's an idea anyway:
Date curr = new Date();
Date date = new Date(114, /*114 is 2014 , don't know why*/
6,
16,
8, 45, 0);
System.out.println(curr);
System.out.println(date);
Date x = new Date(curr.getYear() - date.getYear() ,
curr.getMonth() - date.getMonth(),
curr.getDate() - date.getDate(),
curr.getHours() - date.getHours(),
curr.getMinutes() - date.getMinutes(),
curr.getSeconds() - date.getSeconds() );
String startDateString = "2017-03-08";
String finishDateString = "2017-03-10";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.ENGLISH);
LocalDate startDate = LocalDate.parse(startDateString, formatter);
LocalDate finishDate = LocalDate.parse(finishDateString, formatter);
Integer day = finishDate.compareTo(startDate);
Integer day will be 3. It means that the difference between two dates equals 3 days

Incrementing date by 18years in java

1.I want to set the setMaxSelectableDate=18years in JDateChooser so i provided it the date by incrementing milliseconds but how should i increment it by 18years.
2.Incrementing by 18years the calculation comes out to be 365*18*24*60*60*1000=56764800000 which gives me error integer number to large.
Date max=new Date();
Date oth1=new Date(max.getTime() + (365*18*24*60*60*1000)); //days*hours*minutes*seconds*milliseconds
SimpleDateFormat maxdateFormatter1 = new SimpleDateFormat("MMM d,yyyy hh:mm:ss a");
String maxdate=maxdateFormatter1.format(oth1);
DateChooser_V1.setMaxSelectableDate(new java.util.Date(maxdate));
Let java.util.Calendar do this work for you:
Calendar c = Calendar.getInstance();
c.setTime(oldDate);
c.add(Calendar.YEAR, 18);
Date newDate = c.getTime();
Which takes care of leap years, historical GMT offset changes, historical Daylight Saving Time schedule changes etc.
You need to use a long. You can achieve this by adding an L to your number:
365L* ...
With JodaTime
DateTime in18Years = new DateTime( ).plusYears( 18 );
Here is how to convert to java.util.Date
Date in18Years = new DateTime( ).plusYears( 18 ).toDate( );
You cannot willy-nilly add seconds (or millseconds) and expect calendar calculations to come out right. Basically it takes some extra effort to account for all of those leap-years, leap seconds, and daylight savings shifts.
Until Java 1.8 comes out, use java.util.Calendar instead of java.util.Date, there are really good reasons that java.util.Date has practically everything in it deprecated. While it looks good in the beginning, with enough use you will find it often "just doesn't work (tm)".
GregorianCalendar now = new GregorianCalendar();
now.add(Calendar.YEAR, 18);
And that's assuming that you didn't overflow Integer.MAX_INT.
I would use a Calendar object to achieve this:
Calendar cal = Calendar.getInstance();
Date dt = new Date();
...
// Set the date value
...
cal.setTime(dt);
cal.add(Calendar.YEAR, +18);
dt = cal.getTime();
Hope this helps you

How to convert Formatted Date (yyyy-MM-dd) to Unix time in Java?

How to convert Formatted date (yyyy-MM-dd) to Unix time in Java?
I want to declare a date using
Date birthday = new Date(y_birthday, m_birthday, d_birthday);
but this constructor has been deprecated, so I got to use the other constructor which uses Unix timestamp
So, you have the date as a string in the format yyyy-MM-dd? Use a java.text.SimpleDateFormat to parse it into a java.util.Date object:
String text = "2011-12-12";
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
Date date = df.parse(text);
edit If you need a java.sql.Date, then you can easily convert your java.util.Date to a java.sql.Date:
java.sql.Date date2 = new java.sql.Date(date.getTime());
Use a calendar object if you want more control of the date object
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, 2011);
calendar.set(Calendar.MONTH, 11); // indexed month (December)
calendar.set(Calendar.DATE, 12);
Date date = new Date(calendar.getTime().getTime());
The hours, minutes, seconds etc of the current time will be set though so you may want to set those to 0 (manually per field)
If you're using Java 7 then I think there's some much nicer stuff you can use for handling dates

Number of seconds in "HH:MM:SS"

What's the best way to get the number of seconds in a string representation like "hh:mm:ss"?
Obviously Integer.parseInt(s.substring(...)) * 3600 + Integer.parseInt(s.substring(...)) * 60 + Integer.parseInt(s.substring(...)) works.
But I don't want to test that, and reinvent the wheal, I expect there is a way to use DateTimeFormat or other classes from standard libraries.
Thanks!
Based on pakores solution:
DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
Date reference = dateFormat.parse("00:00:00");
Date date = dateFormat.parse(string);
long seconds = (date.getTime() - reference.getTime()) / 1000L;
reference is used to compensate for different timezones and there is no problem with daylight saving time because SimpleDateFormat does NOT use the actual date, it return the Epoc date (January 1st, 1970 = no DST).
Simplifying (not much):
DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = dateFormat.parse("01:00:10");
long seconds = date.getTime() / 1000L;
but I would still have a look at Joda-Time...
An original way:
The Calendar version (updated with the suggestions in the comments):
DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = dateFormat.parse(string);
//Here you can do manually date.getHours()*3600+date.getMinutes*60+date.getSeconds();
//It's deprecated to use Date class though.
//Here it goes an original way to do it.
Calendar time = new GregorianCalendar();
time.setTime(date);
time.setTimeZone(TimeZone.getTimeZone("UTC"));
time.set(Calendar.YEAR,1970); //Epoc year
time.set(Calendar.MONTH,Calendar.JANUARY); //Epoc month
time.set(Calendar.DAY_OF_MONTH,1); //Epoc day of month
long seconds = time.getTimeInMillis()/1000L;
Disclaimer: I've done it by heart, just looking at the documentation, so maybe there is a typo or two.
joda-time is 1 options. infact i prefer that library for all date manipulations. I was going thru the java 5 javadoc and found this enum class which is simple and useful for you. java.util.concurrent.TimeUnit. look at the convert(...) methods. http://download.oracle.com/docs/cd/E17476_01/javase/1.5.0/docs/api/java/util/concurrent/TimeUnit.html
Here is the link to a Java example of time formatting.
http://download.oracle.com/docs/cd/E17409_01/javase/tutorial/i18n/format/simpleDateFormat.html

Categories