How to limited String in Android - java

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();

Related

Unparseable date with SimpleDateFormatter

I have a date that keeps giving me an error of
java.text.ParseException: Unparseable date: " 5 April 2017  "
All other dates (without word months) work fine
The code I am using is below:
VisitDate=VisitDate.trim();
if (VisitDate.matches(".*[a-z].*")){
SimpleDateFormat changeDate = new SimpleDateFormat("dd_MMM_yy", Locale.UK);
//Convert the string to a date
Date date = changeDate.parse(VisitDate);
//Reformat the date the way I like it
SimpleDateFormat dt1 = new SimpleDateFormat("dd_MM_yy");
//Convert back into a string
try {
VisitDate=dt1.format(date);
if(VisitDate==null){
SimpleDateFormat dt2 = new SimpleDateFormat("dd MM yy");
//Convert back into a string
VisitDate=dt2.format(date);
if(VisitDate==null){
SimpleDateFormat dt3 = new SimpleDateFormat("dd MMMM yy");
//Convert back into a string
VisitDate=dt3.format(date);
if(VisitDate==null){
SimpleDateFormat dt4 = new SimpleDateFormat("d_MMM_yy");
//Convert back into a string
VisitDate=dt4.format(date);
if(VisitDate==null){
SimpleDateFormat dt5 = new SimpleDateFormat("d_MMMM_yy");
//Convert back into a string
VisitDate=dt5.format(date);
if(VisitDate==null){
SimpleDateFormat dt6 = new SimpleDateFormat("dd_MMM_yy");
//Convert back into a string
VisitDate=dt6.format(date);
if(VisitDate==null){
SimpleDateFormat dt7 = new SimpleDateFormat("dd_MMM_yyyy");
//Convert back into a string
VisitDate=dt7.format(date);
if(VisitDate==null){
SimpleDateFormat dt8 = new SimpleDateFormat("dd_MMMM_yyyy");
//Convert back into a string
VisitDate=dt8.format(date);
if(VisitDate==null){
VisitDate=VisitDate.replaceAll("\\s", "");
SimpleDateFormat dt9 = new SimpleDateFormat("dd MMMM yyyy");
//Convert back into a string
VisitDate=dt9.format(date);
}
}
}
}
}
}
}
}
} catch (Exception e) {
Logger.error(e+"->No visit Date frmo here with the original date as: "+date);
}
}
Happy to read your expressed interest in the modern date and time classes, here’s just a snippet to get you started:
String visitDate = " 5 April 2017 ";
DateTimeFormatter parseFormatter
= DateTimeFormatter.ofPattern("d MMMM uuuu", Locale.UK);
visitDate = visitDate.trim();
LocalDate date = LocalDate.parse(visitDate, parseFormatter);
// reformat to the string we like
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd_MM_uu");
visitDate = date.format(formatter);
The result is
05_04_17
I have spelled visitDate with a small v since the Java coding conventions recommend that variable names begin with a small letter.
The uu is subtle and probably something you can ignore. It’s a signed year where 0 equals 1 BC, -1 equals 2 BC and so forth. Assuming none of your dates are that old, you can use u and y interchangeably.
I believe that neither SimpleDateFormat.format() nor LocalDate.format() will ever return null, so all your null checks are superfluous.
Link for further reading: Oracle tutorial: Trail: Date Time
You only have one SimpleDateFormatter being used for parsing:
SimpleDateFormat changeDate = new SimpleDateFormat("dd_MMM_yy", Locale.UK);
//Convert the string to a date
Date date = changeDate.parse(VisitDate);
It is using the format dd_MMM_yy, however you are passing 4 digits for the year.
The rest of your SimpleDateFormatters are being used for formatting to a string, not parsing from a string. Only the first one will be called, since it will be able to produce a string given a valid date, and the following null checks will stop any other formatters from being used.
You have the input string to parse like this: " 5 April 2017 ". But you have no pattern match for this input
First please trim the space of input string
Second please change the format of your string or add another pattern to parse this string, because you have month April with 5 letter, but you have no pattern with MMMMM. Usually the month will be shorten to 3 letter like: April -> Apr, March -> Mar ...

Date format conversion adding extra year

I need to format my input date string.
Input date string : 28-01-1983(dd-MM-yyyy)
Expected date string : 1983-01-28 (yyyy-MM-dd)
I have used below program. But I am not getting correct output.
public static String formateDate(String oldFormat, String newFormat, String date) {
final String OLD_FORMAT = oldFormat;
final String NEW_FORMAT = newFormat;
String oldDateString = date;
String newDateString = null;
try {
SimpleDateFormat sdf = new SimpleDateFormat(OLD_FORMAT);
Date d = sdf.parse(oldDateString);
sdf.applyPattern(NEW_FORMAT);
newDateString = sdf.format(d);
}
catch (ParseException e) {
e.printStackTrace();
}
return newDateString;
}
Calling method :
public static void main(String[] args) {
String formatDob = formateDate("MM-dd-yyyy", "yyyy-dd-MM", "28-01-1983");
System.out.println("Formated DOB:"+formatDob);
}
Right now I am getting output : Formated DOB:1985-01-04
Why my code produce wrong output? I am using JDK 1.7
You are passing month as 28 in your old format which says (12 + 12 + 4) means April month of the upcoming third year.
So, your old format(MM-dd-yyyy) will parse date as (1983 + 2 years) = 1985 and 4th month of the third year which is April so you will have date 1st April 1985. Your old date format should be dd-MM-yyyy.
Consider the first part of the conversion
You have format of MM-dd-yyyy and you have the date string of 28-01-1983
As there is not a month 28 I suggest that the format should be dd-MM-yyyy
Change
formateDate("MM-dd-yyyy", "yyyy-dd-MM", "28-01-1983");
to
formateDate("MM-dd-yyyy", "yyyy-dd-MM", "01-28-1983");
Your were passing date in place month.

convert multiple date strings to long

I have 2 strings: "Sun Jun 23" and "22:45". I want to get the long (millisecond?) representation of the date that is indicated by this 2 strings plus the actual year.
I am trying something like this:
String s1 = "Sun Jun 23";
String s2 = "22:45";
long date = new SimpleDateFormat("EEE MMM dd").parse(s1).getTime()
+ new SimpleDateFormat("HH:mm").parse(s2).getTime();
When I convert back the long date format to String with
private SimpleDateFormat sdf;
sdf = new SimpleDateFormat("yyyy.MM.dd_HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
console.getOut().println(sdf.format(date));
I got "1970.06.23_20:45:00"
This indicates 2 problems:
This doesn't contain the current year. How can I add it?
Why did I 'lost' 2 hours (from 22:45 to 20:45)
Try concat the string then parse the date and get the time
String completeTime = s1 + " " + s2;
SimpleDateFormat sdf = new SimpleDateFormat ("EEE MMM dd HH:mm")
Date date = sdf.parse(completeTime)
long millis = date.getTime()
Edit..
Completely did read the whole question before sorry...
The year is not read in anywhere by your date so you will either have to add it or read it in from somewhere, if it is the year, I suggest using a Calendar object to get it
The Timezone information in the parse from your millis long seems to causing the time difference, you could try using "GMT+2" to correct this but this may not always be correct. If you take out the settin gof the timezone does it change your result?
I got a bit further, but got a different issue:
String s1 = "Sun Jun 23";
String s2 = "22:45";
SimpleDateFormat f = new SimpleDateFormat("YYYY EEE MMM dd HH:mm");
f.setTimeZone(TimeZone.getTimeZone("GMT")); //thanks for the timezone hints!
Date d;
long date;
int year;
try {
year = Calendar.getInstance().get(Calendar.YEAR);
String fullDate = year + " " + s1 + " " + s2;
d = f.parse(fullDate);
date = d.getTime();
SimpleDateFormat sdf2;
sdf2 = new SimpleDateFormat("yyyy.MM.dd_HH:mm:ss");
sdf2.setTimeZone(TimeZone.getTimeZone("GMT"));
console.getOut().println(sdf2.format(date));
} catch (ParseException e) {
e.printStackTrace();
}
This prints out:
2012.12.30_22:45:00.
Timezone now looks okay (as I see 22:45),
fullDate contains the proper string ("2013 Sun Jun 23 22:45").
Why do I not get the correct date?

limiting the length of a string

I have a string that says 15:00:00 how can I limit the length of the string so it says 15:00 ?
For dates
Date date = new Date();
SimpleDateFormat sd = new SimpleDateFormat("HH:mm");
sd.format(date); //will return formatted date
Try this,
String time = "15:00:00";
time = time.subString(0,time.lastIndexOf(":"));
try this:
String time = "15:00:00";
String str =time.substring(0,result.length() - 3);

SimpleDateFormat, need textual Month

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);

Categories