Get date/time with SimpleDateFormat - android

folks!
I've got such date entry:
<pubDate>23/06/2011 11:57</pubDate>
I try to parse it:
mDateFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm");
item_tag.getChild("pubDate").setEndTextElementListener(new EndTextElementListener() {
#Override
public void end(String body) {
date= new GregorianCalendar(0,0,0).getTime();
try {
date=mDateFormat.parse(body);
} catch (ParseException e) {
e.printStackTrace();
}
}
});
But I get something like that: 23/57/2011 11:57 I get minutes instead of month value
What's wrong with my code?

Your code looks OK. Check out what do you really pass to this method, or just check what will happen if you insert line like:
body = "23/06/2011 11:57";

As shown in examples here, you should use '-' instead of '/' when instantiating a mask.

Related

get twitter user timeline and apply filters

I am implementing twitter kit for android in my application following the official documentation (https://github.com/twitter/twitter-kit-android/wiki).
I make the login and I get the basic data correctly and without problem.
When I want to get the user's tweets, or time line, the way to do it is indicated but always shown in a list or recyclerview (https://github.com/twitter/twitter-kit-android/wiki/Show-Timelines)
I have seen these examples also in stackoverflow where the same solution is given, but always turning the data into a list or recyclerview
My question: is there any way to get just the JSON response to the query, ?
The answers I have found do not specifically respond to this.
In the following way it is possible to obtain a list of tweets, but I can not apply search filters like the date, or keywords (untilDate, etc)
void writeInFile()
{
userTimeline = new UserTimeline.Builder()
.userId(userID)
.includeRetweets(false)
.maxItemsPerRequest(200)
.build();
userTimeline.next(null, callback);
}
Callback<TimelineResult<Tweet>> callback = new Callback<TimelineResult<Tweet>>()
{
#Override
public void success(Result<TimelineResult<Tweet>> searchResult)
{
List<Tweet> tweets = searchResult.data.items;
for (Tweet tweet : tweets)
{
String str = tweet.text; //Here is the body
maxId = tweet.id;
Log.v(TAG,str);
}
if (searchResult.data.items.size() == 100) {
userTimeline.previous(maxId, callback);
}
else {
}
}
#Override
public void failure(TwitterException error)
{
Log.e(TAG,"Error");
}
};
You get all the necessary data in the
public void success(Result<TimelineResult<Tweet>> searchResult)
callback.
You have your list of tweets from
searchResult.data.items;
and then you can pick only the data you need. Tweet class has a lot of data inside that you can use. Here are the docs.
If you compare it with JSON api response you can see that you have the same info.
All you need to do is get data from your Tweet object and filter based on it. For example let's get only tweets that were created during last 6 hours:
List<Tweet> tweets = searchResult.data.items;
List<Tweet> filteredTweets = new ArrayList<>();
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
cal.add(Calendar.HOUR_OF_DAY, -6);
Date sixHoursBefore = cal.getTime();
for (Tweet tweet : tweets)
{
Date tweetCreatedAtDate = null;
try {
tweetCreatedAtDate = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy").parse(tweet.createdAt);
if (tweetCreatedAtDate.after(sixHoursBefore)) {
filteredTweets.add(tweet);
}
} catch (ParseException e) {
e.printStackTrace();
}
}
There twitter returns createdAt in format Wed Aug 27 13:08:45 +0000 2008 which is not very handy, but we can parse it.
I'd recommend you to refactor it a bit, pull out calendar and parsing logic to a separate functions, but you can get the idea from the code above.

Get date from Edittext to DayDecorator

first of all thanks for reading this :)
Here is my problem.
I got an EditText (User date input) and i want to get a colored background on my CustomCalander for that day using DayDecorator.
//EditText I want to get the date
huablauf = (EditText)getActivity().findViewById(R.id.huablauf);
//adding calendar day decorators
List<DayDecorator> decorators = new ArrayList<>();
decorators.add(new Markierung());
calendarView.setDecorators(decorators);
calendarView.refreshCalendar(currentCalendar);
//class Markierung
private class Markierung implements DayDecorator {
EditText huablauf=(EditText)getActivity().findViewById(R.id.huablauf);
#Override
public void decorate(DayView dayView) {
// I know I have to get my String to a date and then get it to
// dayView.getDate()! But my code didnĀ“t work
dayView.getDate();
int color = Color.parseColor("#f9acb8");
dayView.setBackgroundColor(color);
}
Hope you can understand my problem and anybody can help :)
Thx from Bavaria
Try this:
#Override
public void decorate(DayView dayView) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy",Locale.getDefault());
try{
if(dayView.getDate().equals(dateFormat.parse(huablauf.getText().toString()))){
int color = Color.parseColor("#f9acb8");
dayView.setBackgroundColor(color);
}
} catch (Exception e){
//Handle exception.
}

ical4j DateTime parse exception

Using ical4j 1.0.6, I'm trying to instantiate a DateTime from a "DTSTART..." String. The constructor is throwing a ParserException even for the examples listed as valid in the DateTime documentation and ical4j wiki
String date = "DTSTART;TZID=US-Eastern:19970714T133000";
try {
DateTime dt = new DateTime(date);
} catch (ParseException e) {
e.printStackTrace(); //always thrown
}
java.text.ParseException: Unparseable date: "DTSTART;TZID=US-Eastern:19970714T133000" (at offset 0)
I've tried setting KEY_RELAXED_PARSING to true, to no avail.
What am I doing wrong?
Looking at the javadoc, the constructor DateTime(String) says:
Constructs a new DateTime instance from parsing the specified string representation in the default (local) timezone.
So I guess the "DSTART" and "TZID" parts of the string are too much.
To set a specific TimeZone, read the section Working with timezones.
I ended up using this code
String[] parts = property.split(":");
if (parts.length > 1) {
try {
String timezone = parts[0].replace("DTSTART;TZID=", "");
DtStart start = new DtStart();
start.getParameters().add(Value.DATE_TIME);
start.getParameters().add(new TzId(timezone));
start.setValue(parts[1]);
} catch (ParseException e) {
e.printStackTrace();
}
}

date display in listview in android

I am trying to display a date in descending order in listview in android... I have written a program... It is showing it correctly, but when the first date of the month coming, the last month date are not displaying only one date is showing... What is the reason? How do I improve my code? Please guide me..
my code is here...
public void datesadd()
{
listview.setAdapter(new ListAdapter(this));
cc1=Calendar.getInstance();
int mon1=cc1.getTime().getDate();
Date dd=new Date();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
while(mon1>=count)
{ pos=0;
line=new HashMap<String,String>();
String cdat=String.valueOf(cc1.get(Calendar.DATE));
#SuppressWarnings("deprecation")
String mons=String.valueOf(cc1.get(Calendar.MONTH));
String day1=String.valueOf(cc1.getTime().getDay());
#SuppressWarnings("deprecation")
String year1=String.valueOf(cc1.get(Calendar.YEAR));
try {
dd=format.parse(year1+"-"+mons+"-"+cdat);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
line.put("yeari", year1);
line.put("mont",mons);
line.put("dayi",dd.toString().substring(0, 3));
line.put("datei",cdat);
mon1--;
cc1.add(Calendar.DATE, -1);
Log.v("", "line");
disp.add(line);
// here disp is ArrayList<Hashmap<String,String>> object, i was declared it on top of my main program
}
}
I don't think you're going about date iteration right -- you're just iterating over the value in miliseconds.
Consider this:
/* From your code I'm not sure what count is, but you get the idea, you need
* a Date object here or you can just use a for() loop if you know the number
* |
* V */
while (cc1.getTime().after(count)) {
cc1.add(Calendar.DAY_OF_YEAR /*or month, year, whatever*/, -1);
// and then continue with your own code
line = new HashMap<String,String>();
String cdat = String.valueOf(cc1.get(Calendar.DATE));
// ...
}

Android: Display time using simpledateformat

I am trying to display the time that a user enters, either in a toast or using a basic println command. If the time is in the correct format, I want to enter it in a database along with the current time.
Here is what I have so far:
public void addListenerOnButton ()
{
spinner_hours = (Spinner)findViewById(R.id.hours);
spinner_minutes = (Spinner)findViewById(R.id.minutes);
btnSubmit = (Button) findViewById(R.id.btnSubmit);
btnSubmit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Date time;
String enteredTime= String.valueOf(spinner_hours.getSelectedItem())+String.valueOf(spinner_minutes.getSelectedItem())+"00";
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
try {
time= format.parse(enteredTime);
System.out.println(enteredTime);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Toast.makeText(MainActivity.this,
// "Your alarm has been set for : " + time,
// Toast.LENGTH_SHORT).show();
}
});
}
If I put the toast (commented below) inside the try block, it doesnt show up when I run the app. If I put a system.out.println it does not print anything. How do I print the entered time?
Also, I want to enter the current time in the same format ("HH:mm:ss") in the database. Any ideas on how to do that?
It's probably throwing an exception, since System.out.println should work. Try replacing this:
String enteredTime= String.valueOf(spinner_hours.getSelectedItem())+String.valueOf(spinner_minutes.getSelectedItem())+"00";
by this:
String enteredTime= String.valueOf(spinner_hours.getSelectedItem())+ ":" + String.valueOf(spinner_minutes.getSelectedItem())+":00";
It seems you're missing the : between hour and minutes and before 00 and the parsing is failing.
First try to print the value got from the Spinner
System.out.println(spinner_hours.getSelectedItem().toString());
System.out.println(spinner_minutes.getSelectedItem().toString());
If this doesn't has any value then the problem is here.

Categories

Resources