Getting time from String - java

My Java code must get string "HH:MM" from console and needs to operate with it.
is there possible to parse such time from string in order to add, for example,2 hours.
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter some time:");
String enteredTime = in.readLine();
// here I want to get time in some variable
Thanks!
As result I have to get three dates and define is there three date between another dates .
I understand that I can split string on parts and work with their, but I'm lloking for simple way to operate with such times.
I found good solution:
SimpleDateFormat parser = new SimpleDateFormat("HH:mm");
Date ten = parser.parse("10:00");
Date eighteen = parser.parse("18:00");
try {
Date userDate = parser.parse(someOtherDate);
if (userDate.after(ten) && userDate.before(eighteen)) {
...
}
} catch (ParseException e) {
// Invalid date was entered
}

sdf = new java.text.SimpleDateFormat ("HH:mm");
sdf.parse ("13:47");

I understand you want to do some date arithmetics like adding durations to dates. Then you should definitely use joda time instead of java.util.Date and Calendar.
Joda gives you Period and Duration entities and a nice and readeable API.

Related

java.text.ParseException: Unparseable date when trying to convert "2013-07-01T04:37:14.771468Z" into Local time

I need to convert UTC time string I get into local time using following method,
String dateCreate = "2013-07-01T04:37:14.771468Z"
DateFormat dfParse = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss'Z'");
dfParse.setTimeZone(TimeZone.getTimeZone("UTC"));
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
df.setTimeZone(TimeZone.getTimeZone("Asia/Colombo"));
java.util.Date dateTime;
dateTime = dfParse.parse(dateCreate);
String dteCreate = df.format(dateTime);
Can someone plese give me a solution for this.? :)
EDIT: Now that I've checked it supports this easily, I'd strongly recommend that you use Joda Time. Its ISO-8601 parser works fine:
String dateCreate = "2013-07-01T04:37:14.771468Z";
DateTimeFormatter formatter = ISODateTimeFormat.dateTime();
DateTime parsed = formatter.parseDateTime(dateCreate);
By default that will convert to the system default time zone, but you can change that behaviour with calls on DateTimeFormatter.
Joda Time is also a much cleaner API than the built-in one - you'll find any date/time code is easier to write and easier to read.
Look at your input data and your pattern:
String dateCreate = "2013-07-01T04:37:14.771468Z";
DateFormat dfParse = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss'Z'");
They don't match at all. You need something like:
// Don't use this directly!
DateFormat dfParse = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSS'Z'");
dfParse.setTimeZone(TimeZone.getTimeZone("UTC"));
Or:
// Don't use this directly!
DateFormat dfParse = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSX");
The latter will cope with any ISO-8601 time zone; the former restricts to UTC.
Unfortunately, the above will end up with the wrong number of milliseconds as it will take all the microseconds to be milliseconds. I don't know of a way of avoiding this in Java... you may need to trim the string first. For example:
// Remove the sub-millisecond part, assuming it's three digits:
int firstPartLength = "yyyy-MM-ddTHH:mm:ss.SSS".length();
String noMicros = dateCreate.substring(0, firstPartLength) +
dateCreate.substring(firstPartLength + 3);
// Now we've got text without micros, so create an appropriate pattern
DateFormat dfParse = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX");
Date date = dfParse.parse(noMicros);
Alternatively, if you know it's always going to end with "Z":
int firstPartLength = "yyyy-MM-ddTHH:mm:ss.SSS".length();
String noMicros = dateCreate.substring(0, firstPartLength);
DateFormat dfParse = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
dfParse.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = dfParse.parse(noMicros);
This is irritating, and it would be nice to be able to tell Java to treat any digits after the dot as "fractions of a second" but I don't know of any way of doing that using SimpleDateFormat. Note that you wouldn't be able to represent the sub-millisecond value using just Date anyway.
This is xsd dateTime format. You should use javax.xml.bind.DatatypeConverter for that
Calendar c = DatatypeConverter.parseDateTime(lexicalXSDDateTime);
Note that for SmipleDateFormat S means number of milliseconds so it will parse 771468 as 771468 ms not 0.771468 sec which adds extra 771 secs to the result date
Formatting part is OK

How to display the date format in android?

String date="21-04-2013";
In my android application
Here i want to display the date in the following format like "21" is a separate string and month is like "Apr" as a separate string and year is like "13"as a separate string without using String functions.Can anybody plz give some suggestions to convert in this format?any date function is available?
You'll want to take a look at the SimpleDateFormat class for parsing the date string. In order to end up separate strings without using string functions, you'll probably need multiple formatters for the output too. It would look somewhat like this:
String date = "21-04-2013";
SimpleDateFormat dateFormatter = new SimpleDateFormat("dd-MM-yyyy"); // input date
Date outDate = dateFormatter.parse(date);
SimpleDateFormat dayFormatter = new SimpleDateFormat("dd"); // output day
SimpleDateFormat monthFormatter = new SimpleDateFormat("MMM"); // output month
SimpleDateFormat yearFormatter = new SimpleDateFormat("yy"); // output year
String day = dayFormatter.format(outDate);
String monthy = monthFormatter.format(outDate);
String year = yearFormatter.format(outDate);
If you were to use String.split(), you could get rid of at least two of the formatters in above snippet.
This is the class you'll need: DateFormat
Examples are provided in the link, but in short, you'll first need to parse the date, and then format the date again.

ignore any white space or new line in java date compare

I am trying to compare two dates in java. While the following code works fine, I would like to handle situations where there may be some alterations in the date format of the input dates.
For example, in the below code, the date format of the two dates are as yyyy/mm/dd hh:mm:ss am. But sometimes there are some additional white space/new line characters found in the input date and this causes exception.
java.text.ParseException: Unparseable date: "02/14/2013
07:00:00 AM"
The following is the code am trying to execute.
try
{
Date date1 = (Date)DATE_FORMAT_yyyy_mm_dd_hh_mm_ss.parse(slaTime); // usually the data comes as 2013/02/03 09:09:09 AM
Date date2 = (Date)DATE_FORMAT_yyyy_mm_dd_hh_mm_ss.parse(actualTime);// usually the data comes as 2013/02/03 09:06:09 AM
// a error occurs
if(date1.before(date2))
{
return "True";
}
else
{
return "False";
}
}
catch (ParseException e)
{
e.printStackTrace();
}
how to handle this?
One of the simplest solutions is to strip all whitespace from the String version of the date before you parse it. Alter your date format to not include any spaces (yyyy/MM/ddhh:mm:ssaaa), and use this to parse the stripped string.
final DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/ddhh:mm:ssaaa");
final String dateStr = "02/14/2013 07:00:00" +
"\n AM";
Date failingDate = dateFormat.parse(dateStr);
Date passingDate = dateFormat.parse(dateStr.replaceAll("\\s",""));
For Month in year Use M instead of m
Correct date format would be yyyy/MM/dd hh:mm:ss aaa. And If there is any additional space or new line then you must remove it other wise it will failed to parse your string to date, your should exact match with format .
I would suggest you to remove all space and new line character then parse it.
you can use format like - yyyy/MM/ddhh:mm:ssaaa where there is no space. And replaceAll your space and new Line with empty String.
Date date = new SimpleDateFormat("yyyy/MM/ddhh:mm:ssaaa").parse("2013/02/1407:00:00AM");
and you actual code could be like -
dateString = dateString.replaceAll("\\s","");
SimpleDateFormat("yyyy/MM/ddhh:mm:ssaaa").parse(dateString);

How can I parse a period of date into a String[ ] day by day in Java?

For example,the input parameters are 2011-01-01 and 2012-01-01,
and I want to parse this period day by day like 2011-01-01~2011-01-02, 2011-01-02~2011-01-03...
Finally,store them in a array of String?
Thanks in advance.
For parsing the date from a string, I recommend using SimpleDateFormat.
That way you will obtain a Date object. Use the Date object to create a GregorianCalendar.
Then, you can use GregorianCalendar's add method to increase it one day at a time until you reach your end date.
Here's a code example:
String dateString1 = "2011-01-01";
String dateString2 = "2012-01-01";
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
List<String> dates = new ArrayList<String>();
Date startDate = dateFormat.parse(dateString1);
Date endDate = dateFormat.parse(dateString2);
GregorianCalendar calendar = new GregorianCalendar();
calendar.setTime(startDate);
while (calendar.getTime().before(endDate)) {
dates.add(dateFormat.format(calendar.getTime()));
calendar.add(Calendar.DAY_OF_MONTH, 1);
}
This puts your dates in a list. You can convert it to an array like this:
String[] datesArray = dates.toArray(new String[0]);
You should really work on your accept rate. but the basic method would go like this :
psuedo-code:
Date first = "2011-01-01";
Date last = "2012-01-01";
Calendar cal = new Calendar(first);
List<Date> dates = ...;
while (first.before(last)) {
cal.addDays(1);
dates.add(cal);
}
This should be really easy to implement using GregorianCalendar, or you can check out joda-time which would make this a whole lot of easy...

Regex HHmm validation- Java

I need to validate a textBox entry which contains time.
Time should be in HH:mm format and in 24-hour format.
For eg:
09:00, 21:00, 00:00, etc.,
Invalid entries:
2534, 090, *7&**, etc.,
If time entered is in HHmm format, then I need to append a ':'
to the entry.
For e.g:
If textBox entry= 0930, it should be changed to 09:30
This is what I have so far:
String textBoxVal = getTextBoxValue();
String colonCheck = ":";
if (!textBoxVal.contains(colonCheck)){
textBoxVal = textBoxVal.substring(0,2) + ":" + textBoxVal.substring(2,4);
}
But as is obvious, this code isn't going to work for all cases.
I'm not very familiar with regex, so any help on how this can be achieved using regex in Java, would be helpful!Thanks!
Solution using DateFormat, as pointed by Ranhiru
String theTime = "23:55";
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm"); //HH = 24h format
dateFormat.setLenient(false); //this will not enable 25:67 for example
try {
System.out.println(dateFormat.parse(theTime));
} catch (ParseException e) {
throw new RuntimeException("Invalid time "+theTime, e);
}
The following will do the trick for you
str = str.replaceAll("([01][0-9]|[2][0-3]):?([0-5]\d)", "$1:$2");
This will change 2300 to 23:00 and leave 23:00 as is.
You can also use (?:[01][0-9]|[2][0-3]):?[0-5]\d just for validation.
Just a further note - even though this one does the trick, if it is date validation that you want, then I would go the DateFormat route.
//Assuming text to match is in var mytext
var re=new RegExp(/^(\d\d):{0,1}(\d\d)$/);
var match=re.exec(mytext);
if (!match) alert("Bad value!");
else mytext=match[1]+':'+match[2];

Categories

Resources