Hi I have the following date string format:
June-2008
July-2008
March-2010
May I enquire what is the java regex to extract out whatever the month and year value into separate string each. The delimeter here is the "-" sign
Any values from the start to the end of the "-" sign is the month, anything after the "-" sign is the year value.
The following is what I would like to achieve
String m = March
String y = 2010
Thank all for your help!
Don't use a regex. Use String#split():
String[] parts = "June-2008".split("-", 2); // or .split("-")
String m = parts[0]; // "June"
String y = parts[1]; // "2008"
Even better, use SimpleDateFormat, and you'll have a proper Date to work with:
DateFormat df = new SimpleDateFormat("M-y");
Date myDate = df.parse("June-2008");
I want to extend the answer given by Matt Ball. If you want to split that string and willing to use other than String#split() you can use StringUtils of Apache Commons Lang. It has various String utility methods.
An example:
String strDate = "June-2008";
String[] parts = StringUtils.split(strDate, '-');
String month = parts[0]; // "June"
String year = parts[1]; // 2008
Also if you want to get a java.util.Date object then Joda Time may helps you. I personally prefer this api rather java.util.Date as it is far more rich, easy-to-use, less error-pron.
Now we can manipulate that String as:
String strDate = "June-2008";
DateTimeFormatter formatter = DateTimeFormat.forPattern("MMMM-yyyy");
DateTime dateTime = formatter.parseDateTime(strDate); // parse it
Date javaDate = dateTime.toDate(); // a java.util.Date object
int year = dateTime.getYear(); // 2008
String month = dateTime.month().getAsText(); // June
Hope this will help you. Thanks.
Related
I am having issues with SimpleDateFormat changing the appearance of a datetimestamp when I parse a String and then format the resulting Date.
The code snippet below demonstrates the issue. Note: I know it seems futile to parse and then format the same date with the same SimpleDateFormat, but this is a contrived example just to demonstrate the principle:
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
String dateStringToConvert = "2016-03-12T22:00:00.000-00:00";
try {
Date date = dateFormat.parse(dateStringToConvert);
String convertedDateString = dateFormat.format(date);
System.out.println("Wanted : " + dateStringToConvert);
System.out.println("Actual : " + convertedDateString);
} catch (ParseException e) {
e.printStackTrace();
}
The output of this is as follows:
Wanted : 2016-03-12T22:00:00.000-00:00
Actual : 2016-03-12T22:00:00.000Z
As this date is to be used in an automated test to fill in a form, it is important that the format of the datetimestamp remains exactly the same after being parsed and formatted by the SimpleDateFormat, so I don't want it to remove the -00:00 and add a Z.
It seems like a very simple problem, but I can't find any obvious answers.
I'm afraid SimpleDateFormat can't help you. This class is poorly designed and very limited, not to mention all the problems it has: https://eyalsch.wordpress.com/2009/05/29/sdf/
If you have Java 8, just use the java.time API. Not sure why you are converting a String to a Date just to convert it back to another String, but if you want the final result as a String with -00:00 as offset, then you can do:
DateTimeFormatter fmt = new DateTimeFormatterBuilder()
.appendPattern("yyyy-MM-dd'T'HH:mm:ss.SSS")
// offset, use "-00:00" when it's zero
.appendOffset("+HH:MM", "-00:00")
// create formatter, always work in UTC
.toFormatter().withZone(ZoneOffset.UTC);
String dateStringToConvert = "2016-03-12T22:00:00.000-00:00";
Instant instant = fmt.parse(dateStringToConvert, Instant::from);
String result = fmt.format(instant);
System.out.println(result);
This will print:
2016-03-12T22:00:00.000-00:00
As Jon Skeet said in a comment, there is no way around hardcoding this special requirement.
DateTimeFormatter formatter;
String dateStringToConvert = "2016-03-12T22:00:00.000-00:00";
if (dateStringToConvert.endsWith("-00:00")) {
formatter = new DateTimeFormatterBuilder()
.appendPattern("uuuu-MM-dd'T'HH:mm:ss.SSS'-00:00'")
.parseDefaulting(ChronoField.OFFSET_SECONDS, 0)
.toFormatter();
} else {
formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSxxx");
}
OffsetDateTime dateTime = OffsetDateTime.parse(dateStringToConvert, formatter);
String convertedDateString = dateTime.format(formatter);
System.out.println("Wanted : " + dateStringToConvert);
System.out.println("Actual : " + convertedDateString);
This prints
Wanted : 2016-03-12T22:00:00.000-00:00
Actual : 2016-03-12T22:00:00.000-00:00
As has also already been said, the offset of -00:00 (negative zero) isn’t equivalent to zero offset, so it really isn’t correct at all to parse the string into an OffsetDateTime as I do. A correct version of the code would parse into a LocalDateTime in this case and format the LocalDateTime back using the same formatter. It would overall be a bit longer, on the other hand you would no longer need the parseDefaulting call.
I am using and warmly recommending java.time, the modern Java date and time API. Because Date, DateFormat and SimpleDateFormat are long outmoded and have proven to be troublesome to work with in varying degrees. The modern API is so much nicer.
Link: Oracle tutorial: Date Time explaining how to use java.time
Try this:
String pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";
SimpleDateFormat df = new SimpleDateFormat(pattern) {
public StringBuffer format(Date date, StringBuffer prefix, FieldPosition fieldPosition) {
StringBuffer finalStr = super.format(date, prefix, fieldPosition);
finalStr = finalStr.insert(finalStr.length()-2, ':');
finalStr = finalStr.deleteCharAt(finalStr.length() - 6);
finalStr = finalStr.insert(finalStr.length() - 5, '-');
return finalStr;
};
};
System.out.println(df.format(yourDate));
I am posting DateTime as JSON and it becomes "/Date(1512839439513)/"
i simply want to convert
"/Date(1512839439513)/" to java.util.Date
I have tried this
String date = finalObject.getString("DateCreated");
String datereip = date.replaceAll("\\D+","");
Long timeInMillis = Long.parseLong(datereip);
Date date1=new Date(timeInMillis);
But did not worked...
The way you extract the milliseconds from the string seems to be the problem.
You can try this to extract needed data from the string:
String date = finalObject.getString("DateCreated");
String temp = date.substring(date.indexOf("(") + 1);
String datereip = date.substring(0, date.indexOf(")"));
Long timeInMillis = Long.parseLong(datereip);
Date date1=new Date(timeInMillis);
This assumes that the date string will have only one pair of parenthesis. Also, there are better ways to extract string between 2 chars with Java but that is a topic of another question.
In my application I want to show some text (date) into TextView.
I get this Text from server and I want to show this Text in TextView.
I get this Text from server :
16 Dec 2017
But I want to show such as this :
2017
How can I remove 16 Dec ?
try this
public static String getYyyy(String date) {
String time = date;
try {
SimpleDateFormat format = new SimpleDateFormat("dd MMM yyyy");
Date date1 = format.parse(date);
if (date1 != null) {
time = new SimpleDateFormat("yyyy").format(date1);
}
} catch (ParseException e) {
e.printStackTrace();
}
return time;
}
try this use split()
There are two signature for split() method in java string.
public String split(String regex)
and,
public String split(String regex, int limit)
use split a string in Java is to use .split(" ") which splits a string according to the pattern provided, returning a String array.
sample code
String date="16 Dec 2017";
String [] dateParts = date.split(" ");
String day = dateParts[0];
String month = dateParts[1];
String year = dateParts[2];
You can just separate the string with help of " " i.e. blank space, try to split the string with " " just like this:-
String date = "16 Dec 2017";
String[] date = date.split(" ");
//for only 2017 you can use date[2]
Be aware there are several ways more elegant and correct to do this, normally you use a Date object and just change how it looks like...
but to your wish, my answer:
I wouldnt split because is a waste to create an array for only getting one element of it...
you can use the substring method
String xdate = "16 Dec 2017";
System.out.println(xdate.substring(xdate.length() - 4, xdate.length()));
In java 8 you can do like this :
Date date = new Date(); //Create a Date object with date provided from TextBox
LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
int year = localDate.getYear();
int month = localDate.getMonthValue();
int day = localDate.getDayOfMonth();
Since you only want the year int year = localDate.getYear(); will give you year.
if you want substring of date in which only Year i.e. last 4 number then try below code
String date="16 Dec 2017";
int a = date.length();
String d = date.substring(a-4,a);
You can try this as well rather then split if you have date & time or more date data
String requested_date = "16 Dec 2017";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd MMM yyyy");
Date dateObj = simpleDateFormat.parse(requested_date,new ParsePosition(0));
dateObj.getYear();
I'm so ashamed asking this question, but I have no other choice.
I want to convert this string to date:
2015-11-25T19:36:39.571+06:00
To convert it I use SImpleDateFormat:
String str = "2015-11-25T19:36:39.571+06:00";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
Date date = format.parse(str);
System.out.println(date);
When I launch this code it gives to me java.text.ParseException: Unparseable date: exception.
I don't know why this is happening.
This should work (In java 7)
String str = "2015-11-25T19:36:39.571+06:00";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
Date date = format.parse(str);
System.out.println(date);
XXX is available in Java 7 as Timezone offset, see the Javadoc http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
The issue is because of wrong pattern used.Z isInstead of yyyy-MM-dd'T'HH:mm:ss.SSSZ use pattern yyyy-MM-dd'T'HH:mm:ss.SSSX
Z represents Time zone in RFC 822 time zone format i.e., like this -0800
So, your code will look like this.
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX");
Your pattern does not correspond entirely to the input string, you have a slight type in the time zone part of your format.
Change your format in the following way to make it work:
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
Or change your input string to:
String str = "2001-07-04T12:08:56.235-07:00";
Please use Below Pattern it works fine
"yyyy-MM-dd'T'HH:mm:ss.SSSXXX"
There is a problem with your input String according to the pattern you have used.
remove the last ':' from the str variable.
change:
String str = "2015-11-25T19:36:39.571+06:00";
in to:
String str = "2015-11-25T19:36:39.571+0600";
and run. It'll work.
Here is the fiddle:
working link
Good day,
Please correct me if my title and question is not correct.
Normally I just convert a String to a date format all in numeric, example :
mm/dd/yyyy to yyyy-mm-dd as 01/02/2000 to 2000-02-01
or any other style/pattern.
I am thinking can I convert it to a date format with contains of characters month or not, example :
mm/dd/yyyy to dd-MMM-yyyy as 10/09/2013 to 09-Oct-2013
Which is the month no longer display in numeric, but in alpha.
I am work in Java, Struts framework.
Kindly advise.
Hope this helps. You can choose multiple patterns which can be found at link below. Here is an example how to use it
Multiple patterns can be found here
final String OLD_FORMAT = "dd/MM/yyyy";
final String NEW_FORMAT = "yyyy/MMM/dd";
// August 12, 2010
String oldDateString = "12/08/2010";
String newDateString;
SimpleDateFormat sdf = new SimpleDateFormat(OLD_FORMAT);
Date d = sdf.parse(oldDateString);
sdf.applyPattern(NEW_FORMAT);
newDateString = sdf.format(d);
`