Subtract char of digits like normal integers - java

I have two strings which can be seen as time stamps:
String min="2017-04-15 13:27:31";
String max="2017-04-15 13:40:01";
Assume we want to find out the time passed from first time stamp to the second one. If there was only the time and no date included, I could get it using my following code:
String[] partsMin=min.split(":");
String[] partMax=max.split(":");
int diffZero=Integer.parseInt(partMax[0])-Integer.parseInt(partsMin[0]);
int diffOne=Integer.parseInt(partMax[1])-Integer.parseInt(partsMin[1]);
int diffOTwo=Integer.parseInt(partMax[2])-Integer.parseInt(partsMin[2]);
diffInSec=diffZero*3600+diffOne*60+diffOTwo;
So here is the question. How to get the job done while there is a date within the time stamp?

I would construct LocalDateTime instances from it.
Then i would get the milliseconds from it and substract startTime from EndTime.
What is remaining are the milliseconds passed between the two. A DateTimeFormatter is helpful as well for this purpose.
String strMin = "2017-04-15 13:27:31";
DateTimeFormatter formatterTime = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime dateTimeMin = LocalDateTime.parse(strMin, formatter);
String strMax = "2017-04-15 13:40:01";
LocalDateTime dateTimeMax = LocalDateTime.parse(strMax, formatter);
long minutes = ChronoUnit.MINUTES.between(dateMin, dateMaxto);
long hours = ChronoUnit.HOURS.between(dateMin, dateMax);
If you want to get the milliseconds:
long millisPassed = dateMax.toEpochMilli() - dateMax.toEpochMilli();

Use the java date time libraries (even the old Date class would be fine for this) to parse the string into a proper object.
Depending on the date time library you chose you can then look at the difference between them. The simplest would be something like:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date date1 = sdf.parse(str1);
Date date2 = sdf.parse(str2);
long differenceInSeconds = (date2.getTime()-date1.getTime())/1000;
The new Java 8 time classes would also allow you to do this and would be better to learn going forwards. I can't remember the syntax for that off the top of my head though.

Did you try with replace all the other part of your String like this :
String[] partsMin = min.replaceAll("\\d+-\\d+-\\d+", "").trim().split(":");
String[] partMax = max.replaceAll("\\d+-\\d+-\\d+", "").trim().split(":");

Doing this in your code:
int diffZero=Integer.parseInt(partMax[0])
is the same as doing:
int diffZero=Integer.parseInt("2017-04-15")
that is generating an Exception(NumberFormatException)
you should better try to PARSE those strings min and max into a date
Edit:
you can inspect your code/ variables: and see that splitting to ":" is not giving you back the correct array since the element at index 0 is holding more information than you need...
but as I said before, you are going on the wrong path, dont re invent the wheel and look how practical will get using the APIs that java has for us:
String min = "2017-04-15 13:27:31";
String max = "2017-04-15 13:40:01";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime dateTimeMin = LocalDateTime.parse(min, formatter);
LocalDateTime dateTimeMax = LocalDateTime.parse(max, formatter);
long days = ChronoUnit.DAYS.between(dateTimeMin, dateTimeMax);
long minutes = ChronoUnit.MINUTES.between(dateTimeMin, dateTimeMax);
System.out.println(days);
System.out.println(minutes);

use SimpleDateFormat to parse the date string, and do operation on Date result, you will get right value. This works well for date between '2017-02-28 23:59:59' and '2017-03-01 00:00:01'
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date1 = format.parse("2017-02-28 23:59:59");
Date date2 = format.parse("2017-03-01 00:00:01");
long time1 = date1.getTime();
long time2 = date2.getTime();
long diff = time2 - time2; // should be 2000

Related

How to calculate Time ago in in java(jsp)

friends
im new using date and time in java.
I stored date and time in String which is the current time similarly I have one more string variable which has the post time
now I want to calculate the ago time even in seconds on any
the string has date and time in this format yyyy/MM/dd HH:mm:ss
can some one help me
Thank you
here is the code
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
LocalDateTime currentTime = LocalDateTime.parse(d_tt, formatter);
LocalDateTime postTime = LocalDateTime.parse(post_time, formatter);
long seconds = ChronoUnit.SECONDS.between(postTime, currentTime);//(error here)
error "ChronoUnit cannot be
resolved"
For this case it is best to use LocalDateTime.
First you have to convert the two strings into a LocalDateTime
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
LocalDateTime currentTime = LocalDateTime.parse(currentTimeString, formatter); // Or use LocalDateTime.now()
LocalDateTime postTime = LocalDateTime.parse(postTimeString, formatter);
These objects can then be used to determine the time between them. There are two possibilities to do this. All of them give the same result, which you can use to determine the time between them according to your own preferences.
Possibility 1:
long seconds = postTime.until(currentTime, ChronoUnit.SECONDS);
Possibility 1:
long seconds = ChronoUnit.SECONDS.between(postTime, currentTime);
You can also get more information here:
Introduction to the Java 8 Date/Time API
Java 8: Difference between two LocalDateTime in multiple units

Change date from MM/dd to yyyy-MM-dd'T'HH:mm:ss.SSZ in Java

I have a String that formatted MM/dd. I would like to convert it to a Date in format yyyy-MM-dd'T'HH:mm:ss.SSZ.
DateFormat df = new SimpleDateFormat("MM/dd");
String strDate = "06/05";
Date date = new Date();
date = df.parse(strDate);
This makes it a Date, but in the original format.
System.out.println(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSZ").format(date));
This returns the correct month and day, but nopthing else.
1970-06-05T00:00:00.00-0400
Any idea how I can make it return
CURRENT_YEAR-06-05TCURRENT_TIME
In the question, the date format pattern indicates a desire for 2-digit fractional seconds. SimpleDateFormat cannot do that.
The newer Java 8 Time API can, and you should be using that anyway.
If you're running on Java 6 or 7, get the ThreeTen-Backport library.
To parse a MM/dd formatted string and get a full timestamp with current year and time-of-day, in the default time zone, use the following code:
String strDate = "06/05";
MonthDay monthDay = MonthDay.parse(strDate, DateTimeFormatter.ofPattern("MM/dd"));
ZonedDateTime date = ZonedDateTime.now().with(monthDay);
System.out.println(date.format(DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSZ")));
Sample Output
2020-06-05T14:52:48.45-0400
I recommend to make use of java.time package. There you go:
var ds = "01/12";
var df = java.time.format.DateTimeFormatter.ofPattern("MM/dd");
var dt = java.time.MonthDay.from(df.parse(ds)).adjustInto(java.time.LocalDateTime.now());
Then you can convert dt to java.util.Date or whatever you like. Or simply use one of java.time formaters to get the desired output.
You are creating a date with only month and day
If you want to use the current year and time, you can create a calendar object and edit the month and day
For something this simple I suggest a different approach, get current time then set month and day from the original string THEN format.
String str = "08/09";
String[] split = str.split("/");
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MONTH, Integer.parseInt(split[0]));
calendar.set(Calendar.DAY_OF_MONTH, Integer.parseInt(split[1]));
System.out.println(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS").format(calendar.getTime()));
String strDate = "06-05";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-"+strDate+"'T'HH:mm:ss.SSZ");
System.out.println(sdf.format(new Date()));
the output:
2020-06-05T23:00:45.306+0400

android getDate from milliseconds stored in String field

I have a date stored in a String field in SQLITE with the String value
"/Date(1411472160000+0100)/"
how can I convert this back into a date format , the code below doesn't work. I think I need to convert from the milliseconds first but I cant see how to even get the above text into a long format first ?
any suggestions ?
Date convertedDate = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm",
java.util.Locale.getDefault());
convertedDate = dateFormat.parse(dateString);
return dateFormat.format(convertedDate);
Well, a substring from the indexOf("(") to the indexOf("+") and you should find the date in milli.
From there, I believe you can find the date ;)
String s = "/Date(1411472160000+0100)/";
s = s.substring(s.indexOf("(") + 1, s.indexOf("+"));
Date d = new Date(Long.parseLong(s));
With the same structure, you can find the timezone (+0100) (from "+" to ")") and work with a Calendar to find the right time for the right time area.
First you have to parse out the time value from String i.e. "1411472160000+0100" part.
Here in "1411472160000+0100" , "+0100" is the timezone info. If you don't want to consider the timezone, then you can take following approach.
Approach-1
long timestamp = 1245613885;
Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(TimeZone.getDefault());
calendar.setTimeInMillis(timestamp * 1000);
int year = calendar.get(Calendar.YEAR);
int day = calendar.get(Calendar.DATE);
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
then to get the date in your specified format you can use-
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateString = sdf.format(calendar.getTime());
System.out.println(dateString); // 2009-06-21 15:51:25
Besides this approach, there is an excellent Java Date library called JodaTime.
If you want to incorporate the timezone info , you can refer to this constructor from JodaTime.
http://www.joda.org/joda-time/apidocs/org/joda/time/DateTime.html#DateTime-long-org.joda.time.DateTimeZone-

How to format time including milliseconds

I'm trying to get a time string in the format of YYYYMMDD-HHMMSSMilliseconds in Android
Ex: 20130312-1723437520 (2013 March 12th, 17 Hour 23 Minutes 43 Seconds 7520 Milliseconds)
Time now = new Time();
now.setToNow();
String snapshotTime = now.format("yyyyMMdd-HHmmss");
First of all, above code doesn't even work properly. snapshotTime is always set to the format string itself.
Second of all, according to the Android documentation, there's no way to record milliseconds.
How can I accomplish this?
See the SimpleDateFormat class, you can format a Date object into the required format (upper-case S will give millis)
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Date now = new Date();
String str = fmt.format(now);
That said, using Joda Time is usually a good idea (Proguard will strip code you don't use).
You'll have to use the strftime formatting, as noted in the Android docs.
Time now = new Time();
now.setToNow();
String snapshotTime = now.format("%Y%m%d-%H%M%S");
If you really want to use milliseconds than I would recommend SimpleDateFormat.
Try getting the time as unix timestamp with milliseconds from
long currentTime = System.currentTimeMillis();
or convert your time to milliseconds:
long currentTime = now.toMillis(true);
Then you can convert this to your desired date:
Time now = new Time();
now.set(currentTime);
String snapshotTime = now.format("%Y%m%d-%H%M%S")+""+(currentTime%1000);
Didn't test it but hope it works :)
I would recommend to use this little library, it's very helpful when working with dates. Have a look at the DateTimeFormatter class.
As an alternative use Calendar and SimpleDateFormater (you'll have to adjust the format string of course, see this for explanation of the symbols)
Calendar c = new GregorianCalendar();
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy-SSSS");
String date = sdf.format(c.getTime());
You can try this:
public static String format() {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd-HHmmssSSS");
Date now = new Date();
return simpleDateFormat.format(now);
}

Incrementing date in yyyymmddhhmmss.mmm format in Java

I want to increment the milliseconds in any given date in the format yyyymmddhhmmss.mmm in each iteration. mmm here represents milliseconds. And I want to perfom this operation in Java 1.5.
For example: 20120823151034.567 should be incremented to 20120823151034.568
You can use long milli-seconds which make incrementing trivial.
final String input = "20120823151034.567";
final DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss.SSS");
Date d = df.parse(input);
d.setTime(d.getTime()+1);
System.out.println(df.format(d));
I wouldn't use Calendar as its very slow.
You can parse String to Date object and use getTime() and setTime(long l) to modify date. Then you can convert Date object back to String. For parsing String and converting Date object back to String you can use SimpleDateFormat class.
The best class to use for this operation is Calendar. You set it to the desired date, and then use
myCalendar.add(Calendar.MILLISECOND, 1);
to advance it by one millisecond. Use DateFormat to produce string representations.
This gives you what you want. It will work across any day/month/year boundary, as well as handling the start and end of daylight saving time.
final String input = "20120823151034.567";
final DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss.SSS");
final Calendar c = Calendar.getInstance();
c.setTime(df.parse(input));
c.add(Calendar.MILLISECOND, 1);
System.out.println(df.format(c.getTime()));
You can use Calendar Class as well as Date Class for this....
Date Class:
final String dateStr = "20120823151034.567";
final DateFormat format = new SimpleDateFormat("yyyyMMddHHmmss.SSS");
Date date = format.parse(input);
date.setTime(date.getTime()+1);
System.out.println(format.format(date));
Calendar Class:
final String dateStr = "20120823151034.567";
final DateFormat format = new SimpleDateFormat("yyyyMMddHHmmss.SSS");
Calendar c = Calendar.getInstance();
c.setTime(format.parse(dateStr ));
c.add(Calendar.MILLISECOND,1);
System.out.println(format.format(c.getTime()));
In both cases, format.parse() has the potential to throw a ParseException, which you will need to catch and handle.
An alternative without using Calendar (although, Calendar is fine)
final String input = "20120814120000.111";
final DateFormat format = new SimpleDateFormat("yyyyMMddHHmmss.SSS");
Date date = new format.parse(input);
long time = date.getTime();
Date incrementedDate = new Date(time + 1);
System.out.println(format.format(date));

Categories

Resources