I have a string in the format of:
3:00 pm on Aug 28
What would be the best way to verify that a valid time and valid date is contained within this string? My first thought was to split the string and use two regexs to match a time and the other one to match that specfic date format (abbreviate month day). However I'm having a little bit of trouble with the second regex (the one for the specfic date format). How else could one go about verifying the string is in the correct format?
You can try this:
public boolean isValid( String dateStr ) {
// K: hour of the day in am/pm
// m: minute of a hour
// 'on': static text
// MMM: name of the month with tree letters
// dd: day of the month (you can use just d too)
DateFormat df = new SimpleDateFormat( "K:m a 'on' MMM dd", Locale.US );
try {
df.parse( dateStr );
return true;
} catch ( ParseException exc ) {
}
return false;
}
More about the format string here: http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
Use java.text.SimpleDateFormat. Use a format string something like HH:mm aa 'on' MMM dd.
You may have to add yyyy to the format string and 2012 to your input.
Use SimpleDateFormat and make sure it doesn't use lenient parsing:
try {
DateFormat df = new SimpleDateFormat("h:mm a 'on' MMM dd", Locale.US);
df.setLenient(false);
Date dt = df.parse(s);
} catch (ParseException pe) {
// Wrong format
}
Related
I have String with date format dd.MM.yyyy, and I want to upload it to my MS SQL server, but the required format is yyyy-MM-dd. I tried this but it doesn't work like I want to.
String expDate = mDatePickerBtn.getText().toString();
Date date = null;
SimpleDateFormat format = new SimpleDateFormat("dd.MM.yyyy");
try {
date = format.parse(expDate);
expDate = date.getYear() + "-" + date.getMonth() + "-" + date.getDay();
} catch (ParseException e) {
e.printStackTrace();
}
For example if I pass 31.12.2032 to the expDate, the date variable will cointain "Fri Dec 31 00:00:00: GMT+01:00 2032", and the expDate will contain "132-11-5" and I don't even know why.
I would use DateTimeFormatter but my minimal API level is 24.
My question is: where did I make mistake or how else can I get correct format out of this?
Go compile your app with Android Gradle Plugin 4.0.0+ and use java.time then like this:
public static void main(String[] args) {
// get / provide the String to be parsed
String expDate = "31.12.2032";
// provide a pattern that parses such a date
String pattern = "dd.MM.uuuu";
// create a DateTimeFormatter with this pattern
DateTimeFormatter dtf = DateTimeFormatter.ofPattern(pattern);
// parse the String with the DateTimeFormatter
LocalDate expLocalDate = LocalDate.parse(expDate, dtf);
// print the default format of a LocalDate
System.out.println(expLocalDate);
// print the LocalDate using the pattern created for parsing
System.out.println(expLocalDate.format(dtf));
// create a totally different DateTimeFormatter inline and format the date differently
System.out.println(expLocalDate.format(DateTimeFormatter.ofPattern("EEE, dd 'of' MMMM uuuu",
Locale.ENGLISH)));
}
The output would be this:
2032-12-31
31.12.2032
Fri, 31 of December 2032
Try this way
String expDate = mDatePickerBtn.getText().toString();
Date date = null;
SimpleDateFormat format = new SimpleDateFormat("dd.MM.yyyy");
try {
date = format.parse(expDate);
SimpleDateFormat format1 = new SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH);
format1.format(date);
expDate = format1.format(date);
} catch (ParseException e) {
e.printStackTrace();
}
I am trying to take date in string and its input format string and converting the date in output format. However after conversion into Date, the java code increases the number of hours by one. I am not able to understand what causes the bug.
My Code:
try {
DateFormat outputFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
DateFormat inputFormat = new SimpleDateFormat(format);
Date date = inputFormat.parse(parameterValue);
parameterValue = outputFormat.format(date);
return parameterValue;
} catch (ParseException ex) {
// take action
}
format string: ddMMMyyyy / hh:mm z
Input Date: 07DEC2015 / 10:02 GMT
Output Date: 07/12/2015 11:02:00
outputFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
resolved it.
If you don't want to use timezone, in java 8 you can use LocalDate/LocalTime/LocalDateTime:
LocalDateTime localDateTimeInstance = LocalDateTime.parse(dateToBeConverted, DateTimeFormatter.ofPattern(formatOfDateToBeConverted));
return localDateTimeInstance.format("dd/MM/yyyy hh:mm:ss");
/*
Also check out ZoneDate, ZoneTime (for timezone)
Checkout - LocalDate, LocalTime
*/
I have this as a string 02/06/2012 1:25 PM EST
I want to use SimpleDateFormat to return "Feb" from that data
Here is what I tried
SimpleDateFormat gottenDate = new SimpleDateFormat("MMM");
String month = "";
try {
month = gottenDate.format(gottenDate.parse("02/06/2012 1:25 PM EST"));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Unfortunately gottenDate.parse("02/06/2012 1:25 PM EST") gets a parse exception when the SimpleDateFormat documents say it should work.
If I do SimpleDateFormat gottenDate = new SimpleDateFormat("MM"); with two M's instead of 3, it returns "02" for me, as expected. The documents say that 3 or more M's should return a textual month. This doesn't happen, why? And yes, by now I could have made a string array of months and matched them to the numberic month SDF returned for me, but I am curious.
How do I make it work for me, thank you!
Exception is expected in your case:
SimpleDateFormat gottenDate = new SimpleDateFormat("MMM");
gottenDate.parse("02/06/2012 1:25 PM EST");
"gottenDate" is set up to parse a string if it matches "MMM" pattern. The following should work:
SimpleDateFormat gottenDate = new SimpleDateFormat("MMM");
gottenDate.parse("Feb");
Hopefully you can see what's going on here.
You need a format to parse the date: MM/dd/yyyy, and once you have a Date object from this first date format, you need a second one: MMM, to format the date as you want.
Formatting with MM will give you the month on two digits, and parsing with MMM will expect an abbreviated textual month, and won't parse 02.
You need two separate SimpeDateFormat instances with corresponding format strings to parse source date and format it back into short month form. Your format instance can't parse full date because it expecting only month in specified string.
SimpleDateFormat monthDate = new SimpleDateFormat("MMM");
SimpleDateFormat gottenDate = new SimpleDateFormat("dd/MM/yyyy h:mm a z");
String month = "";
try {
month = monthDate .format(gottenDate.parse("02/06/2012 1:25 PM EST"));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Not sure about format of your source string, complex format strings are little tricky.
This is the code that will get MonthName to you:
public String getMonthName(String dtstr, String fmt) throws ParseException {
SimpleDateFormat gottenDate = new SimpleDateFormat(fmt);
SimpleDateFormat month = new SimpleDateFormat("MMM");
Date dt = gottenDate.parse(dtstr);
return month.format(dt);
}
Call it like this:
System.out.println(getMonthName("01/06/2012 1:25 PM EST"), "M/d/y");
OUTPUT:
Feb
Well, others were faster answering, but I think this will do what you want.
String date_str = "02/06/2012 1:25 PM EST";
SimpleDateFormat in_format = new SimpleDateFormat("MM/dd/yyyy h:mm aa zzz");
SimpleDateFormat out_format = new SimpleDateFormat("MMM");
Date my_date = in_format.parse(date_str);
String out_str = out_format.format(my_date);
System.out.println(out_str); // Prints Feb
Dates and times can get complicated because of the way people in different record times. The best reference I've found for understanding all this is here:
http://www.odi.ch/prog/design/datetime.php
Just to provide an alternative solution, since your jobs is to "extract" the month of a Date, I think Calendar best fits the job.
// Construct a Date object
final DateFormat df = new SimpleDateFormat("M/d/y");
final Date originalDate = df.parse("02/06/2012 1:25 PM EST");
final Calendar c = Calendar.getInstance();
c.setTime(originalDate); // set the calendar Date
// Extract the month
String month = c.getDisplayName(Calendar.MONTH, Calendar.SHORT, Locale.US);
System.out.println(month);
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();
}
String temp_date="07/28/2011 11:06:37 AM";
Date date = new Date(temp_date); //Depricated
SimpleDateFormat sdf = new SimpleDateFormat("MMM-dd-yyyy hh:mm:ss");
String comp_date= sdf.format(date);
System.out.println(comp_date);
This works, But If I use something like this
String temp_date="07/28/2011 11:06:37 AM";
try{
SimpleDateFormat sdf = new SimpleDateFormat("MMM-dd-yyyy hh:mm:ss");
Date comp_date= sdf.parse(temp_date);
System.out.println(comp_date);
}catch(Exception e){
System.out.println(e);
}
This exception is thrown:
java.text.ParseException: Unparseable date: "07/28/2011 11:06:37 AM"
Your parsing pattern is wrong. It does not match the date string representation. The MMM denotes a 3-letter localized month abbreviation, while you have 2-digit month number in your actual date, you need MM. You've also slashes / as date/month/year separator and not -. For the AM/PM marker you also need an a afterwards so that the right hh can be parsed.
This should work:
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a");
For an explanation of those patterns, read the SimpleDateFormat javadoc.
I believe that your concrete functional requirement is to convert the given date string as specified by the pattern MM/dd/yyyy hh:mm:ss a into another date string format, as specified by the pattern MMM-dd-yyyy hh:mm:ss. In that case, you should then have two SimpleDateFormat instances, one which parses the string in the given pattern to a Date and another which formats the parsed Date to the given pattern. This should do what you want:
String inputDate = "07/28/2011 11:06:37 AM";
Date date = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a").parse(inputDate);
String outputDate = new SimpleDateFormat("MMM-dd-yyyy HH:mm:ss").format(date);
System.out.println(outputDate); // Jul-28-2011 11:06:37
Note that I changed hh in output to be HH because it would otherwise end up in 1-12 hour representation without an AM/PM marker. The HH represents it as 0-23 hour.
The format you gave the SimpleDateFormat uses - between the month, date, and year. Your string uses slashes.
At first look, it looks as if your format string is wrong.
MMM -- You specified this for the month, but you aren't passing a 3 char month.
Try MM and see if that helps.
Take a look at this for some additional date format information:
http://www.java2s.com/Tutorial/Java/0040__Data-Type/SimpleDateFormat.htm