Get date and time input from text - java

So, I was searching for this for some time but I didn't find an answer. Thats why I'm asking here. My problem goes like this:
With Swing I made an app that will get text from JTextArea and then save it inside a .txt document. Also it will save 2 more files (as .txt documents too). In one, there would be date (i.e 2016.03.05) and in other would be time (i.e 09:50 AM). What I need is compare the date and time to system date and time and check if they match. I only need a way on how to exactly do this, since they are stored as string, what would be good way to compare them to system date and time.
I think that is should be like this:
if(date in date file is equal to system date) {/do stuff}
I wouldn't rly be looking for spoonfeeding, but I need to have a good and efficient way of doing this.

Let's pretend the op has read the date/time strings from a file.
String date = "2016.03.05";
String time = "09:50 AM";
We want to compare that to the "system time" so how about.
LocalDateTime now = LocalDateTime.now();
Now we have a date and time and we want to compare it to the values in the file. One way, is to create a LocalDate object from the date string.
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy.MM.dd");
LocalDate localDate = LocalDate.parse(date, dateFormatter);
if(now.toLocaleDate().equals(localDate)){
//date is equal so now what?
}
We can do the same for the local time.
DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("h:m a");
LocalTime localTime = LocalTime.parse(time, timeFormatter);
if(now.toLocalTime().equals(localTime)){
//do stuff if the time is equal (which it will rarely be)
}

If you are using java 8 then there is a very good article on how to parse a String to Date. Once you parse a String into class LocalDateTime then you can then run:
if(LocalDateTime.now().equals(yourTime)) {
//your code
}
to see if they match.
Please read about java.time package here https://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html
and here is an article about String parsing to date: https://www.linkedin.com/pulse/java-8-javatime-package-parsing-any-string-date-michael-gantman?trk=pulse_spock-articles

Related

java.time.format.DateTimeParseException: could not be parsed at index 0

I am trying to convert a String to timestamp.
my string contains time and time zone ('05:03:05.875+02:00') but I get the following error:
error
java.time.format.DateTimeParseException: Text '05:03:05.875+02:00'
could not be parsed at index 0
Code
String timewithZone= "05:03:05.875+02:00";
DateTimeFormatter formatter=DateTimeFormatter.ISO_OFFSET_DATE_TIME;
final ZonedDateTime a2=ZonedDateTime.parse(timewithZone,formatter);
String timewithZone = "05:03:05.875+02:00";
OffsetTime time = OffsetTime.parse(timewithZone);
System.out.println("Parsed into " + time);
This outputs
Parsed into 05:03:05.875+02:00
Your string contains a time and an offset, but no date. This conforms nicely, neither with an ISO_OFFSET_DATE_TIME nor a ZonedDateTime, but with an OffsetTime, a seldom used class that I think is there exactly because such a thing sometimes occurs in XML.
There is also an ISO_OFFSET_TIME formatter built in, but since this is the default format for OffsetTime we do not need to specify it.
It is failing because your string does not have the date related tokens. Check the example in the official documentation. In order to make it work you will need to add year/month/day data:
String timewithZone= "2018-07-3T05:03:05.875+02:00";
You cannot use the DateTimeFormatter.ISO_OFFSET_DATE_TIME because your date format does not adhere to that.
In fact, you don't even have a real date because there is no date component, only a time component.
You could define your own SimpleDateFormat instance with the format you're receiving, but you'll have to handle the fact that this data isn't really all that useful without date information. For example, that offset doesn't really tell us that much, because it might be in some region's Daylight Savings Time (DST) or not. And this heavily depends on on what actual DATE it is, not just what time.
You'll have to find out what the provider of this data even means with this, because right now you simply don't have enough information to really parse this into a proper date.
If this data just means a simple time stamp, used for for example saying "our worldwide office hours lunch time is at 12:30" then you could us the LocalTime class. That would be one of the few cases where a time string like this without a date is really useful. I have a sneaking suspicion this is not your scenario though.
A workaround may be
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss.SSSz");
String str = "05:03:05.875+02:00";
LocalTime time = LocalTime.parse(str, formatter);
System.out.println(time);
I tried the code in the format what you are getting,
Output :
05:03:05.875
Is this the one you are looking for?

DateTime Manipulation in C# vs Java

I'm new to Java. I have a time I am getting from a web-page, this is in the "hh:mm" format (not 24 hour). This comes to me as a string. I then want to combine this string with todays date in order to make a Java Date I can use.
In C#:
string s = "5:45 PM";
DateTime d;
DateTime.TryParse(s, out d);
in Java I have attempted:
String s = "5:45 PM";
Date d = new Date(); // Which instantiates with the current date/time.
String[] arr = s.split(" ");
boolean isPm = arr[1].compareToIgnoreCase("PM") == 0;
arr = arr[0].split(":");
int hours = Integer.parseInt(arr[0]);
d.setHours(isPm ? hours + 12 : hours);
d.setMinutes(Integer.parseInt(arr[1]));
d.setSeconds(0);
Is there a better way to achieve what I want?
Is there a better way to achieve what I want?
Absolutely - in both .NET and in Java, in fact. In .NET I'd (in a biased way) recommend using Noda Time so you can represent just a time of day as a LocalTime, parsing precisely the pattern you expect.
In Java 8 you can do the same thing with java.time.LocalTime:
import java.time.*;
import java.time.format.*;
public class Test {
public static void main(String[] args) {
String text = "5:45 PM";
DateTimeFormatter format = DateTimeFormatter.ofPattern("h:mm a");
LocalTime time = LocalTime.parse(text, format);
System.out.println(time);
}
}
Once you've parsed the text you've got into an appropriate type, you can combine it with other types. For example, to get a ZonedDateTime in the system time zone, using today's date and the specified time of day, you might use:
ZonedDateTime zoned = ZonedDateTime.now().with(time);
That uses the system time zone and clock by default, making it hard to test - I'd recommend passing in a Clock for testability.
(The same sort of thing is available in Noda Time, but slightly differently. Let me know if you need details.)
I would strongly recommend against using java.util.Date, which just represents an instant in time and has an awful API.
The key points here are:
Parse the text with a well-specified format
Parse the text into a type that represents the information it conveys: a time of day
Combine that value with another value which should also be carefully specified (in terms of clock and time zone)
All of these will lead to clear, reliable, testable code. (And the existing .NET code doesn't meet any of those bullet points, IMO.)
To parse the time, you can do as explained in #Jon Skeet's answer:
String input = "5:45 PM";
DateTimeFormatter parser = DateTimeFormatter.ofPattern("h:mm a", Locale.ENGLISH);
LocalTime time = LocalTime.parse(input, parser);
Note that I also used a java.util.Locale because if you don't specify it, it'll use the system's default locale - and some locales can use different symbols for AM/PM field. Using an explicit locale avoids this corner-case (and the default locale can also be changed, even at runtime, so it's better to use an explicit one).
To combine with the today's date, you'll need a java.time.LocalDate (to get the date) and combine with the LocalTime, to get a LocalDateTime:
// combine with today's date
LocalDateTime combined = LocalDate.now().atTime(time);
Then you can format the LocalDateTime using another formatter:
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm");
System.out.println(combined.format(fmt));
The output is:
16/08/2017 17:45
If you want to convert the LocalDateTime to a java.util.Date, you must take care of some details.
A java.util.Date represents the number of milliseconds since 1970-01-01T00:00Z (aka Unix Epoch). It's an instant (a specific point in time). Check this article for more info.
So, the same Date object can represent different dates or times, depending on where you are: think that, right now, at this moment, everybody in the world are in the same instant (the same number of milliseconds since 1970-01-01T00:00Z), but the local date and time is different in each part of the world.
A LocalDateTime represents this concept of "local": it's a date (day, month and year) and a time (hour, minute, second and nanosecond), but without any relation to a specific timezone.
The same LocalDateTime object can represent different instants in time in different timezones. So, to convert it to a Date, you must define in what timezone you want it.
One option is to use the system's default timezone:
// convert to system's default timezone
ZonedDateTime atDefaultTimezone = combined.atZone(ZoneId.systemDefault());
// convert to java.util.Date
Date date = Date.from(atDefaultTimezone.toInstant());
But the default can vary from system/environment, and can also be changed, even at runtime. To not depend on that and have more control over it, you can use an explicit zone:
// convert to a specific timezone
ZonedDateTime zdt = combined.atZone(ZoneId.of("Europe/London"));
// convert to java.util.Date
Date date = Date.from(zdt.toInstant());
Note that I used Europe/London. The API uses IANA timezones names (always in the format Region/City, like America/Sao_Paulo or Europe/Berlin).
Avoid using the 3-letter abbreviations (like CST or PST) because they are ambiguous and not standard.
You can get a list of available timezones (and choose the one that fits best your system) by calling ZoneId.getAvailableZoneIds().
And there's also the corner cases of Daylight Saving Time (when a LocalDateTime can exist twice or can't exist due to overlaps and gaps). In this case, Jon's solution using ZonedDateTime avoids this problem).

How to reformat the time of Java Time class

I searched topics about formatting time but these were all about Date class or DateTime. I am working with Time class. I created time as:
Time time = new Time(Time.getCurrentTimezone()) ;
time.setToNow();
String berkay = time.toString();
System.out.println(berkay);
When I execute it the output is :
20130417T070525GMT(3,106,0,0,1366182325)
actually date and time is correct (2013-04-17 07:05:25)
but I need to convert it into : 20130417070525 (My reason to do this is I will search database according to date so it is easier to compare times in that format)
How can I convert it?
Try this:
Time time = new Time(System.currentTimeMillis()) ;
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
String date = df.format(time).toString();
System.out.println(date);
EDIT
But as smttsp suggested its much more efficient to store it as timestamp
To convert java.util.Date into String you should consider java.text.SimpleDateFormat.
For using java.util.Date as a parameter of a database query you should pass the Date as is without converting it into any other format.
passing Date parameter to create date range query
<- In the answer there is sample how to create such query.
It is a bit late but if you are working on time and you need to compare or sort, the best way is to use Unix timestamp. It starts from 1-Jan-1970 00:00:00 and increments 1 each second.
It is a long value(64 bit) which is quite efficient to use in both time and space. Here is the website for Unix timestamp conversion.
Also 20130417070525 is 14 char string(at least 15 byte, I guess) and 1366182325 is long(8 byte). So go for long value. U can get it in that way
Date myDate = new Date(); // current time
myDate.getTime(); // converts it to specified format.

Java String to Date Conversion in different format

So i have String trDate="20120106"; and want to get Date trDate=2012-01-06 and am trying to use SimpleDateFormat for changing the pattern but first i get to parse the string and then generate date and then try to call format which gives me back string but i need date, any suggestions, here is the code i have:
String trDate="20120106";
Date tradeDate = new SimpleDateFormat("yyyymmdd", Locale.ENGLISH).parse(trDate);
String krwtrDate = new SimpleDateFormat("yyyy-mm-dd", Locale.ENGLISH).format(tradeDate);
Date krwTradeDate = new SimpleDateFormat("yyyy-mm-dd", Locale.ENGLISH).parse(krwtrDate);
Here is similar question but it does not answer my question
I need converted string in Date format only because i need to pass it to another function that expects Date object only.
Would really appreciate if someone can give example of how to get date in yyyy-mm-dd format from string which is in yyyymmdd format?
--- Answer updated due to commentary ---
Ok, so the API you are using demands a String, which represents a Date in the format of 2012-04-20
You then need to parse the incorrectly formatted Date and then format it again in the needed format.
String trDate="20120106";
Date tradeDate = new SimpleDateFormat("yyyyMMdd", Locale.ENGLISH).parse(trDate);
String krwtrDate = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH).format(tradeDate);
Also note that I changed your "month" designator, as you have made a very common mistake of using m for month. Due to the "hours:minutes:seconds" date formats have two common "names" that both start with m, minutes and months. Uppercase M is therefore used for months, while lowercase m is used for minutes. I'll bet that this is the real reason you're encountering problems.
--- Original post follows ---
If your APIneeds a java.util.Date, then you don't need to do as much as you have. You actually have the java.util.Date with just the two lines
String trDate="20120106";
Date tradeDate = new SimpleDateFormat("yyyymmdd", Locale.ENGLISH).parse(trDate);
But this solution might not make sense without a quick review of what java.util.Dates are. Dates are things, but how they are presented is divorced from what they are.
At any moment in time, there is one Date instance that describes that moment in time. How that Date instance should be presented is not in agreement, it depends heavily on what language the viewer speaks, which country they are in, what rules the country has imposed (daylight savings time), and what their cultural background has done before.
As such, a Date has no single associated presentation. That's why every "get the X" method on Date is deprecated (where X is day, month, hour, year, etc.), with the exception of grabbing the milliseconds from the 0 date (known as the epoch).
So, for every Date that is to be properly presented, you need to convert it to a String using rules that are specific to the language, country, time zone, and cultural precedent. The object that understands these rules and applies them is the DateFormat.
Which means, once you get the Date you don't need to reformat it and re-parse it to get the "right" Date as the two dates should be the same (for the same locale).
Do I understand it well?
You have a method which only accepts Date as parameter, and internally that method converts the Date to a string in the wrong format using toString()?
Best is to modify that method and exchange the use of toString() with SimpleDateFormat.format().
If you can't modify that method, than you can "cheat" with OO, i. e. replace the toString method with your own implementation, for example like this:
public class MyDate {
private static final FMT = SimpleDateFormat("yyyy-mm-dd", Locale.ENGLISH);
MyDate(long time) {
super(time);
}
String toString() {
return FMT.format(this);
}
}
and you call your method with
xxx = myMethod(new MyDate(new SimpleDateFormat("yyyymmdd", Locale.ENGLISH).parse(trDate).getTime()));
But if that method does not use toString internally but SimpleDateFormat with the wrong format, then my proposition does not work.
can you give me an example of how to get date in yyyy-mm-dd format from string which is in yyyymmdd format
A Date objects does not have a format associated with it. Internally it typically just stores a long value.
If some other methods is responsible for printing the date, then you unfortunately have no control over how the resulting output is formatted.
If the String date always comes in the format you have mentioned than you can use the subString method to extract the year, month and day.
String trDate="20120106";
Using the subString method for String extract the Year, month and day
String year = "2012";
String month = "01";
String day = "06";
And parse these to integer. Assuming you will do the parsing of string to integer
int intYear = 2012;
int intMonth = 01;
int intDay = 06;
Calendar calendar= new GregorianCalendar(intYear, intMonth - 1, intDay);
Date date = new Date(calendar);

I want to get a formatted Date in Java

I want to get a new Date object with a SimpleDateFormat applied to it. I would like to do something like:
SimpleDateFormat myFormat = new SimpleDateFormat("dd MMM yyyy kkmm");
Date today = new Date();
today = myFormat.format(today);
I can't do this, because today is a Date, and format returns a String. I also have tried:
Date today;
SimpleDateFormat myFormat = new SimpleDateFormat("dd MMM yyyy kkmm");
try{
today = myFormat.parse((new Date()).toString());
}catch(Exception e){
}
This isn't a good solution, because when I try to use today elsewhere Java complains that today may not have been instantiated. What is a good way to change the format of a Date object (while still keeping it a Date object, and not turning it to a string)?
You are looking at Format and Date wrongly.
Date does not contain format. Date is just a class containing date info like date, month, hours, sec etc.
SimpleDateFormat is the one which tells you the string representation of Date. But there is no date associated with it.
So the idea is when you have to display date or have to store date in some string representation, you will use SimpleDateFormat and pass it the date you want string representation for.
One benefit of doing this way is that, I can use same Date object and can show two different string representations (using two different instances of SimpleDateFormat). And also viceversa, having defined one SimpleDateFormat instance, I can format multiple dates.
Edit:
Now if you want to strip some info from the date. Use
Calendar rightNow = Calendar.getInstance();
Calendar cal = new GregorianCalendar(
rightNow.get(YEAR),
rightNow.get(MONTH),
rightNow.get(DAY_OF_MONTH));
Date now = cal.getTime();
There are other good soln like JodaTime
Ref:
GregorianCalendar
Calendar
Joda Time
I think what you are trying to achieve does not make sense.
A Date object represents time. You can not format it. But, you can get it's string representation in certain format. Like with myFormat.format(today).
I think you're misunderstanding something here about what the Date object is. Date simply holds the information about a point in time - it doesn't have a format at all. When it comes to the String representation of a Date, this is where formatting comes into play. Only worry about the formatting when you are:
Parsing a String representation into a Date object.
Converting a Date back into String representation to display it in a certain way.
Your question doesn't make sense. Formatting a date by definition means converting it to a string using a specific format. The Date object can stay as a Date object. It is only at the point where you wish to convert it to a String that you need to do any formatting.
you cannot associate a format to a Date object instead you can only apply the formats while displaying or other activities,,
Do all processing in the Date object itself and while displaying alone change to the required format,,

Categories