How to convert 08:48 PM time into SQL unixtime? - java

How do I convert 08:48 PM formatted string into SQL Unixtime?
Java 1.5

You need java.text.SimpleDateFormat with the hh:mm a pattern (0-12 hours, minutes, AM/PM marker). Click the link to see the Javadoc with detailed pattern explanations.
String time = "08:48 PM";
Date date = new SimpleDateFormat("hh:mm a").parse(time);
long timestampMillis = date.getTime();
long unixTimestamp = timestampMillis / 1000;
If you actually want to store this in a SQL TIME/TIMESTAMP/DATETIME field with help of JDBC, then wrap it in a java.sql.Time and use PreparedStatement#setTime() to save it.
Time time = new Time(timestampMillis); // Yes, with millis!
preparedStatement.setTime(1, time);
// ...

Assuming you still want today's date, try
String today = new SimpleDateFormat("yyyy-MM-dd ").format(new Date());
long timestamp = new SimpleDateFormat("yyyy-MM-dd hh:mm a").parse(today + "08:48 PM").getTime() / 1000;

Related

How to add current time to a previous date in java?

I was trying to add current time into previous date. But it was adding in current date with time not with previous date.
see my bellow code:
Date startUserDate = ;//this is my previous date object;
startUserDate.setTime(new Date().getTime());// here i'm trying to add current time in previous date.
System.out.println("current time with previous Date :"+startUserDate);
In previous date there is no time and i want to add current time in previous date.I can do this, please help me out.
Use calendar object
Get instance of calendar object and set your past time to it
Date startUserDate = ;
Calendar calendar = Calendar.getInstance();
calendar.settime(startUserDate);
Create new calendar instance
Calendar cal = Calendar.getInstance();
cal.settime(new Date());
format the date to get string representation of time of current date
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
String currentdate = sdf.format(cal.getTime());
split that string to get hour minute and second object
String hh = expiry.split(":")[0];
String mm = expiry.split(":")[1];
String ss = expiry.split(":")[2];
add it to the previous calendar object
calendar .add(Calendar.HOUR_OF_DAY, hh);
calendar .add(Calendar.MINUTE, mm);
calendar .add(Calendar.SECOND, ss);
this date will have current time added to your date
Date newDate = calendar.getTime;
Use Calendar:
first set the date/time of the first calendar object to the old date
object use as second Calendar object to set the current time on the
first calendar object then convert it back to date
as follow:
//E.g. for startUserDate
Date startUserDate = new Date(System.currentTimeMillis() - (24L * 60L * 60L * 1000L) - (60L * 60L * 1000L));//minus 1 day and 1 hour
Calendar calDateThen = Calendar.getInstance();
Calendar calTimeNow = Calendar.getInstance();
calDateThen.setTime(startUserDate);
calDateThen.set(Calendar.HOUR_OF_DAY, calTimeNow.get(Calendar.HOUR_OF_DAY));
calDateThen.set(Calendar.MINUTE, calTimeNow.get(Calendar.MINUTE));
calDateThen.set(Calendar.SECOND, calTimeNow.get(Calendar.SECOND));
startUserDate = calDateThen.getTime();
System.out.println(startUserDate);
The second Calendar object calTimeNow can be replaced with Calendar.getInstance() where it is used.
You can do it using DateFormat and String, here's the solution that you need:
Code:
DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
String timeString = df.format(new Date()).substring(10); // 10 is the beginIndex of time here
DateFormat df2 = new SimpleDateFormat("MM/dd/yyyy");
String startUserDateString = df2.format(startUserDate);
startUserDateString = startUserDateString+" "+timeString;
// you will get this format "MM/dd/yyyy HH:mm:ss"
//then parse the new date here
startUserDate = df.parse(startUserDateString);
Explanation:
Just convert the current date to a string and then extract the time from it using .substring() method, then convert your userDate to a string concatenate the taken time String to it and finally parse this date to get what you need.
Example:
You can see it working in this ideone DEMO.
Which takes 02/20/2002 in input and returns 02/20/2002 04:36:14 as result.
java.time
I recommend that you use java.time, the modern Java date and time API, for your date and time work.
ZoneId zone = ZoneId.systemDefault();
LocalDate somePreviousDate = LocalDate.of(2018, Month.NOVEMBER, 22);
LocalTime timeOfDayNow = LocalTime.now(zone);
LocalDateTime dateTime = somePreviousDate.atTime(timeOfDayNow);
System.out.println(dateTime);
When I ran the code just now — 16:25 in my time zone — I got this output:
2018-11-22T16:25:53.253892
If you’ve got an old-fashioned Date object, start by converting to a modern Instant and perform further conversion from there:
Date somePreviousDate = new Date(1_555_555_555_555L);
LocalDate date = somePreviousDate.toInstant().atZone(zone).toLocalDate();
LocalTime timeOfDayNow = LocalTime.now(zone);
LocalDateTime dateTime = date.atTime(timeOfDayNow);
2019-04-18T16:25:53.277947
If conversely you need the result as an old-fashioned Date, also convert over Instant:
Instant i = dateTime.atZone(zone).toInstant();
Date oldfasionedDate = Date.from(i);
System.out.println(oldfasionedDate);
Thu Nov 22 16:25:53 CET 2018
Link
Oracle tutorial: Date Time explaining how to use java.time.
The getTime method returns the number of milliseconds since 1970/01/01 so to get the time portion of the date you can either use a Calendar object or simply use modula arithmetic (using the above milliseconds value and the MAX millseconds in a day) to extract the time portion of the Date.
Then when you have the time you need to add it to the second date,
but seriously, use http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html
and use things like get (HOUR) and get (MINUTE) etc. which then you can use with set (HOUR, val)
You need to use Calendar class to perform addition to Dateobject. Date's setTime() will set that time in Date object but not add i.e it will overwrite previous date. new Date().getTime() will not return only time portion but time since Epoch. Also, how did you manipulated , startUserDate to not have any time (I mean , was it via Calendar or Formatter) ?
See Answer , Time Portion of Date to calculate only time portion,
long MILLIS_PER_DAY = 24 * 60 * 60 * 1000;
Date now = Calendar.getInstance().getTime();
long timePortion = now.getTime() % MILLIS_PER_DAY;
then you can use something like, cal.add(Calendar.MILLISECOND, (int)timePortion); where cal is Calendar object corresponding to your startUserDate in your code.
Calendar calendar = Calendar.getInstance();
calendar.setTime(startUserDate );
//new date for current time
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
String currentdate = sdf.format(new Date());
String hhStr = currentdate.split(":")[0];
String mmStr = currentdate.split(":")[1];
String ssStr = currentdate.split(":")[2];
Integer hh = 0;
Integer mm = 0;
Integer ss = 0;
try {
hh = Integer.parseInt(hhStr);
mm = Integer.parseInt(mmStr);
ss = Integer.parseInt(ssStr);
}catch(Exception e) {e.printStackTrace();}
calendar.set(Calendar.HOUR_OF_DAY, hh);
calendar.set(Calendar.MINUTE, mm);
calendar.set(Calendar.SECOND, ss);
startUserDate = calendar.getTime();

how to get difference between two date_time

I want to get the difference in seconds between end_date_time and system_date_time using JAVA, for example:
if
end_date_time = 2015-02-21 13:00:00
system_date_time = 2015-02-20 13:00:00
then
difference = 86400
Please tell how can I do this?
If you have a Date type already, it's as simple as:
(System.currentTimeMillis() - myDate.getTime()) / 1000;
If you have a string and need to convert it to a date, you use a SimpleDateFormat instance:
String dateString = "2015-02-21 13:00:00" // end_date_time
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
Date myDate = sdf.parse(dateString);
If you're using Java8, this is much easier:
String dateString = "2007-12-03T10:15:30.00Z";
Instant.now().until(Instant.parse(dateString), ChronoUnit.SECONDS);
Your dateString must be parseable in the ISO format, though:
"yyyy-mm-ddThh:mm:ss.SZ"

Change time in DateFormat on Android

I have date and time extracted from JSON in following format
2013-01-16T13:43:11
I need to convert it to local time of Pakistan and add 5 hours to that time so the result is like:
06:43
How I can achieve this?
Assuming that "2013-01-16T13:43:11" is in GMT
String s = "2013-01-16T13:43:11";
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
df.setTimeZone(TimeZone.getTimeZone("GMT"));
Date date = df.parse(s);
date = new Date(date.getTime() + 5 * 3600 * 1000);
String time = new SimpleDateFormat("HH:mm").format(date);
time will be in your local timezone, so if you are in Pakistan it will be OK
You can use SimpleDateFormat as below:
String strDate = null;
SimpleDateFormat dateFormatter = new SimpleDateFormat(
"hh:mm");
strDate = dateFormatter.format(yourDate);
Hope it helps.
java dateFormat is not threadsafe, use joda time lib instead:
Joda time lib download
you can use withZone method to change time with specific Timezone
DateTime userTime1 = new DateTime();
DateTime eventRecordTime = new DateTime();
userTime1 = DateTime.parse("2012-07-05T21:45:00+02:00");
eventRecordTime = DateTime.parse((String) jo.get("start_time"));
DateTimeZone dtz = userTime1.getZone();
System.out.println(eventRecordTime.withZone(dtz).toString());

How to convert this milliseconds into time (hh:mm a)?

I have milliseconds like "1325085788" i want to convert it on hh:mm a . i know this but return me time 01:34 PM instead of 08:53 PM.Whats problem ?
My code is ::
String created_on = "1325085788";
String pattern = "hh:mm a";
SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
Date date = new Date(Long.parseLong(created_on));
String yourFormatedDate = dateFormat.format(date);
System.out.println("--------> " + yourFormatedDate);
no timezone issue because it give me current time (in india) in iphone app
1325085788 isn't milliseconds. It's seconds. Your expectations are off by a few orders of magnitude, but it's giving you the correct time for the given milliseconds.
If you have seconds and want to go to a Date, then something like this:
import static java.util.concurrent.TimeUnit.*;
String created_on = "1325085788";
long millis = MILLISECONDS.convert(Long.parseLong(created_on), SECONDS);
Date d = new Date(millis);
After that, your date formatting should do the rest of the work.

Convert long time difference to format HH:mm [Java]

How can I convert the difference of the current time a given time to create a string with the time format: HH:mm ? ex. 18:36
I did the following but, it is not 24Hour format, it will add AM/PM to the end, and it is 3 hours off.
java.util.Date today = new java.util.Date();
java.sql.Timestamp ts1 = new java.sql.Timestamp(today.getTime());
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss");
java.util.Date parsedDate = dateFormat.parse(time);
java.sql.Timestamp ts2 = new java.sql.Timestamp(parsedDate.getTime());
long nowTime = ts1.getTime();
long givenTime = ts2.getTime();
long timeDiff = givenTime - nowTime;
//convert to string
java.util.Date d = new java.util.Date(timeDiff);
result = DateFormat.getTimeInstance(DateFormat.SHORT).format(d);
//Outputs: 6:56 PM for example
Once easy thing you can do is call getTime() for both dates and then subtract them like so:
long timeDiff = today.getTime() - ts1.getTime()
That should give you the difference in miliseconds between the two times. After that you know that one second is 1k miliseconds, 1min i 60s, 1h is 60 minutes and so on.
Take a look at Commons Lang DurationFormatUtils.
Or Joda-Time's PeriodFormatter.

Categories