So I'm having a timestamp like for example this one =1570312800
and also the source gives me the start time and the end-time in string format, so let's say it's basically from 18:00 to 01:00 (6PM to 1AM)
I want to calculate the difference between the 2 strings (5 hours), convert that to milliseconds and add it to the timestamp.
Which gets me in trouble is the converting from STRING to MILLISECONDS.
Which would be the cleanest way?
Sample Code:
Calendar c1 = Calendar.getInstance(android.icu.util.TimeZone.getTimeZone("UTC"));
Calendar c2 = Calendar.getInstance(android.icu.util.TimeZone.getTimeZone("UTC"));
SimpleDateFormat sdf = new SimpleDateFormat("HHmm");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
try
{
c1.setTime(sdf.parse("20:00"));
c2.setTime(sdf.parse("1:00"));
}
catch (ParseException e)
{
e.printStackTrace();
}
Log.d("TIME DIFFERENCE", String.valueOf(c2.getTimeInMillis()-c1.getTimeInMillis()));
One way to go about this is by parsing the string to a SimpleDateFormat like below:
Calendar c1 = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
c1.setTime(sdf.parse("20:00"));
System.out.println(c1.getTimeInMillis());
Related
I need to convert a time stamp that currently is in string format "08.00" to a valid time in java so I later can compare time. How do I convert this string to time?
Something like this
DateFormat sdf = new SimpleDateFormat("hh:mm");
Date date = sdf.parse(time);
Instead of using the Date and/or SimpleDateFormat classes, perhaps consider LocalTime
String time = "08:00";
LocalTime lt = LocalTime.parse(time);
System.out.println(lt);
Output:
08:00
And can compare to other times easily with LocalTime::isBefore() or LocalTime::isAfter()
Example
Try below code,
String time = "08.00";
try {
DateFormat sdfInput = new SimpleDateFormat("hh.mm");
Date date = sdfInput.parse(time);
DateFormat sdfOutput = new SimpleDateFormat("hh:mm");
Log.e( "Time: ", sdfOutput.format(date));
} catch (Exception e) {
e.printStackTrace();
}
Output -> Time: 08:00
The easiest way to do so is with a SimplDateFormatter:
DateFormat sdf = new SimpleDateFormat("hh:mm")
Then you can call Date date = sdf.parse(*your time string*)
Now you have your time as a valid Date object.
I have timeformat like this hhmmss="151918"
so you can use any format instead of hhmmss according to your current time format like
"hh.mm" or hh:mm:ss etc
and you can call this method form any where you needed.
fun convertTimeFormat(time:String):String{
var formattedTime=""
try {
val inputFormat: DateFormat = SimpleDateFormat("hhmmss")
val timeObj = inputFormat.parse(time)
Log.d("timeObj",""+timeObj)
formattedTime=SimpleDateFormat("hh:mm aa").format(timeObj)
} catch (e: ParseException) {
e.printStackTrace()
}
return formattedTime
}
Let's have the following:
Date inDbDate = null;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
inDbDate = sdf.parse("2015-09-27 23:24:28.035");
Now, when I output the inDbDate I receive the following:
Sun Sep 27 23:24:28 EEST 2015
So, If I have two dates with millisecond differences, there would be no way to find out or to display it.
How do I compare two Dates with this format - 2015-09-27 23:24:28.035 ?
If you want to compare two Date variables, there are some methods provided after(), before(), equals().
private void someMethod(){
final String dateFormat = "yyyy-MM-dd HH:mm:ss.SSS";
Date firstDate = new Date();
Date secondDate = new Date();
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
try {
firstDate = sdf.parse("2015-09-27 23:24:28.035");
secondDate = sdf.parse("2015-09-27 23:24:28.036");
} catch (ParseException pe) {
pe.getMessage();
}
if(firstDate.after(secondDate)) {
System.out.println("The first date is after the second date");
} else{
System.out.println("The first date is before the second date");
}
}
You can copy and paste the above method into your IDE, then try changing the time in the Date variables and see what the outcome is as well as changing the check performed in the if statement.
If you look at the values in one of the Date objects in your debugger you can see the milliseconds are there, just not shown when printed out in a certain format.
1/ you should parse inDbDate with date format ==> inDbDate = sdf.parse("2015-11-11 23:24:28.035");
2/ you can now compare the two dates
if (inDbDate.compareTo(new Date()) > 0) {
System.out.println("inDbDate is after the current date !!");
}
3/ if you want to display, you format it
System.out.println("current time = " + sdf.format(new Date()));
How to compare two timeStamp and get the difference from those. I am trying to get the duration between two different timeStamps. Using Date, But i am getting exception while comparing.
This how I get the timeStamp 01-08-2013 06:19:35
I am getting exception like java.text.ParseException: Unparseable
date: "01-08-2013 06:19:35"
Convert the date into milliseconds and then you can use
long difference = finalDate.getTime() - initialDate.getTime();
Regarding your ParseException, there is something wrong with parsing pattern for your date formatter. I think this is the correct one "dd-MM-yyyy HH:mm:ss" if you want to parse "01-08-2013 06:19:35"
Joda-Time
Alternatively you can use the Joda-Time library and find the time difference in following way:
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd-MM-yyyy HH:mm:ss");
DateTime finalDate = formatter.parse("someDate1");
DateTime initialDate = formatter.parse("someDate2");
Interval interval = new Interval(finalDate, initialDate);
Calendar thatDay = Calendar.getInstance();
thatDay.set(Calendar.DAY_OF_MONTH,25);
thatDay.set(Calendar.MONTH,7); // 0-11 so 1 less
thatDay.set(Calendar.YEAR, 1985);
Calendar today = Calendar.getInstance(); //THIS IS TO GET TODAY DATE, you can simpy use your two dates
long diff = today.getTimeInMillis() - thatDay.getTimeInMillis(); //result in millis
Here's an approximation...
long days = diff / (24 * 60 * 60 * 1000);
PLUS : To Parse the date from a string, you could use
String strThatDay = "1985/08/25";
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
Date d = null;
try {
d = formatter.parse(strThatDay);//catch exception
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Calendar thatDay = Calendar.getInstance();
thatDay.setTime(d); //rest is the same....
I am trying to get the system date by using the following code . Now i want after adding 123 minutes it should automatically add 2 in hours and three in minutes how is it possible?
I am using the following code.
try{
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
Date date = new Date();
String s = sdf.format(date);
}
catch(Exception ex)
{
ex.printStackTrace();
}
Create a GregorianCalendar object: http://docs.oracle.com/javase/7/docs/api/java/util/GregorianCalendar.html add you hours/minutes/whatever you need to add and then get back a Date
This will work
DateFormat df = new SimpleDateFormat("HH:mm:ss");
Date date = new Date();
System.out.println(df.format(date));
long milSec=date.getTime();
long addMilSec=123*60*1000;
long sum=milSec+addMilSec;
Date d=new Date(sum);
System.out.println(df.format(d));
Create a Calendar object, instead of Date, and use add.
Example:
Calendar c = Calendar.getInstance();
c.add(Calendar.MINUTE, 123);
String s = sdf.format(c.getTime());
try like this
Calendar now = Calendar.getInstance();
now.setTime(YOUR_DATE_OBJECT);//pass your date here
now.add(Calendar.MINUTE, 50);//add 5o minutes
now.add(Calendar.SECOND, -50);// subtract 50 seconds
I'm having a hard time Parsing/Formatting a Date string received back from a web service. I've attempted multiple approaches, but with no luck.
Sample Date String:
2011-10-05T03:00:00Z
Exception:
W/System.err(10072): java.text.ParseException: Unparseable date: "2011-10-05T05:00:00Z" (at offset 10)
W/System.err(10072): at java.text.DateFormat.parse(DateFormat.java:626)
Sample Code:
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:SSSS");
Date date = formatter.parse(info.AiringTime);
I've found that if I remove the "T" between the date and the time and replace it with a space, it will format just fine. Anybody have any suggestions?
--UPDATE--
After looking deeper into the API documentation, I found this:
All response DateTime values are in UTC format. You need to apply the UTC offset to calculate the local time for display.
DateTime is a date-and-time value specified in one of the following formats:
UTC format: YYYY-MM-DDThh:mm:ssZ. For example: 2011-03-15T02:00:00Z.
Local time with an offset: YYYY-MM-DDThh:mm:ss + or - hh:mm (positive or negative offset). For example, for US Pacific time: 2011-03-14T06:00:00 -08:00.
Any suggestions on the UTC format approach?
You could try:
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
String dateString = dateString.replace("Z", "GMT+00:00");
Date date = dateFormat.parse(dateString);
The above code should correctly handle the case where a timezone is specified in the date. As Z represents the UTC/GMT timezone it is replaced by GMT so the SimpleDateFormat can interpret it correctly (i would love to know a cleaner way of handling this bit if anyone knows one).
Try,
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
This pattern should parse the date you provide: "yyyy-MM-dd'T'HH:mm:ss'Z'".
If you want to use SimpleDateFormat and you have a limited number of variations, you can create separate formatters for each pattern and chain them:
Date date = formatter1.parse(info.AiringTime);
if (date == null)
{
date = formatter2.parse(info.AiringTime);
if (date == null)
{
date = formatter2.parse(info.AiringTime);
if (date == null)
{
date = formatter3.parse(info.AiringTime);
}
}
}
or put them in a list and iterate until non-null or no more formatters.
If you have too many patterns for this to be practical, you can parse it yourself or try one of these libraries.
This worked for me
SimpleDateFormat isoDateFormat = new SimpleDateFormat("yyyy-mm-dd'T'hh:mm:ss'Z'");
SimpleDateFormat viewFriendlyDateFormat = new SimpleDateFormat("dd/MMM/yyyy hh:mm:ss aaa");
String viewFriendlyDate = "";
try {
Date date = isoDateFormat.parse(timestamp);
viewFriendlyDate = viewFriendlyDateFormat.format(date);
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat isoDateFormat = new SimpleDateFormat("yyyy-mm-dd'T'hh:mm:ss'Z'");
SimpleDateFormat viewFriendlyDateFormat = new SimpleDateFormat("dd/MMM/yyyy hh:mm:ss aaa");
String viewFriendlyDate = "";
try {
Date date = isoDateFormat.parse(timestamp);
viewFriendlyDate = viewFriendlyDateFormat.format(date);
} catch (ParseException e) {
e.printStackTrace();
}