我正在使用DatePicker,以便用户可以选择日期并找出该特定日期的日出和日落时间。
我使用的网络服务要求日期为snet,格式为dd/MM
,但我希望按钮以DDth MMMM YYYY e.g 21st March 2013
格式显示日期
关于如何进行此操作的任何建议?
以下代码请求:
public class SunriseSunset extends Activity implements OnClickListener {
public Button getLocation;
public Button setLocationJapan;
public TextView LongCoord;
public TextView LatCoord;
public double longitude;
public double latitude;
public LocationManager lm;
public Spinner Locationspinner;
public DateDialogFragment frag;
public Button date;
public Calendar now;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sunrisesunset);
//Date stuff
now = Calendar.getInstance();
date = (Button)findViewById(R.id.date_button);
date.setText(String.valueOf(now.get(Calendar.DAY_OF_MONTH)+1)+"-"+String.valueOf(now.get(Calendar.MONTH))+"-"+String.valueOf(now.get(Calendar.YEAR)));
date.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showDialog();
}
});
}
// More date stuff
public void showDialog() {
FragmentTransaction ft = getFragmentManager().beginTransaction(); //get the fragment
frag = DateDialogFragment.newInstance(this, new DateDialogFragmentListener(){
public void updateChangedDate(int year, int month, int day){
date.setText(String.valueOf(day)+"-"+String.valueOf(month+1)+"-"+String.valueOf(year));
now.set(year, month, day);
}
}, now);
frag.show(ft, "DateDialogFragment");
}
public interface DateDialogFragmentListener{
//this interface is a listener between the Date Dialog fragment and the activity to update the buttons date
public void updateChangedDate(int year, int month, int day);
}
public void addListenerOnSpinnerItemSelection() {
Locationspinner = (Spinner) findViewById(R.id.Locationspinner);
Locationspinner
.setOnItemSelectedListener(new CustomOnItemSelectedListener(
this));
}
private class LongRunningGetIO extends AsyncTask<Void, Void, String> {
protected String getASCIIContentFromEntity(HttpEntity entity)
throws IllegalStateException, IOException {
InputStream in = entity.getContent();
StringBuffer out = new StringBuffer();
int n = 1;
while (n > 0) {
byte[] b = new byte[4096];
n = in.read(b);
if (n > 0)
out.append(new String(b, 0, n));
}
return out.toString();
}
@Override
protected String doInBackground(Void... params) {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
// Finds todays date and adds that into the URL
SimpleDateFormat df = new SimpleDateFormat("dd/MM");
String formattedDate = df.format(now.getTime());
String finalURL = "http://www.earthtools.org/sun/"
+ LatCoord.getText().toString().trim() + "/"
+ LongCoord.getText().toString().trim() + "/"
+ formattedDate + "/99/0";
HttpGet httpGet = new HttpGet(finalURL);
String text = null;
try {
HttpResponse response = httpClient.execute(httpGet,
localContext);
HttpEntity entity = response.getEntity();
text = getASCIIContentFromEntity(entity);
} catch (Exception e) {
return e.getLocalizedMessage();
}
return text;
}
protected void onPostExecute(String results) {
if (results != null) {
try {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
InputSource s = new InputSource(new StringReader(results));
Document doc = dBuilder.parse(s);
doc.getDocumentElement().normalize();
TextView tvSunrise = (TextView) findViewById(R.id.Sunrise);
TextView tvSunset = (TextView) findViewById(R.id.Sunset);
tvSunrise.setText(doc.getElementsByTagName("sunrise").item(0).getTextContent());
tvSunset.setText(doc.getElementsByTagName("sunset").item(0).getTextContent());
} catch (Exception e) {
e.printStackTrace();
}
}
Button b = (Button) findViewById(R.id.CalculateSunriseSunset);
b.setClickable(true);
}
}
class MyLocationListener implements LocationListener {
@Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
}
DateDialogFragment:
import java.util.Calendar;
import richgrundy.learnphotography.SunriseSunset.DateDialogFragmentListener;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.Context;
import android.os.Bundle;
import android.widget.DatePicker;
public class DateDialogFragment extends DialogFragment {
public static String TAG = "DateDialogFragment";
static Context mContext; //I guess hold the context that called it. Needed when making a DatePickerDialog. I guess its needed when conncting the fragment with the context
static int mYear;
static int mMonth;
static int mDay;
static DateDialogFragmentListener mListener;
public static DateDialogFragment newInstance(Context context, DateDialogFragmentListener listener, Calendar now) {
DateDialogFragment dialog = new DateDialogFragment();
mContext = context;
mListener = listener;
mYear = now.get(Calendar.YEAR);
mMonth = now.get(Calendar.MONTH);
mDay = now.get(Calendar.DAY_OF_MONTH);
return dialog;
}
public Dialog onCreateDialog(Bundle savedInstanceState) {
return new DatePickerDialog(mContext, mDateSetListener, mYear, mMonth, mDay);
}
private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
mYear = year;
mMonth = monthOfYear;
mDay = dayOfMonth;
mListener.updateChangedDate(year, monthOfYear, dayOfMonth);
}
};
}
非常感谢您的帮助。
如果需要,请提出问题以便澄清=)
---------------- UPDATE -------------------------
我到了那里,现在更新的代码如下:
public void showDialog() {
FragmentTransaction ft = getFragmentManager().beginTransaction(); //get the fragment
frag = DateDialogFragment.newInstance(this, new DateDialogFragmentListener(){
public void updateChangedDate(int year, int month, int day){
DateFormat format = new SimpleDateFormat("DD MM yyyy"); // could be created elsewhere
now.set(year, month, day);
date.setText(format.format(now.getTime()));
date.setText(String.valueOf(day)+"-"+String.valueOf(month+1)+"-"+String.valueOf(year));
now.set(year, month, day);
}
}, now);
frag.show(ft, "DateDialogFragment"); }
答案 0 :(得分:1)
只需使用其他SimpleDateFormat
格式化即可。
public void updateChangedDate(int year, int month, int day) {
DateFormat format = new SimpleDateFormat("DD MM YYYY"); // could be created elsewhere
now.set(year, month, day);
date.setText(format.format(now.getTime());
}
不幸的是,Java没有提供自动获取序数日期(第2,第13 * *,第21等)的正确后缀。
答案 1 :(得分:0)
public void showDialog() {
FragmentTransaction ft = getFragmentManager().beginTransaction(); //get the fragment
frag = DateDialogFragment.newInstance(this, new DateDialogFragmentListener(){
public void updateChangedDate(int year, int month, int day){
now.set(year, month, day);
date.setText(DateFormat.format("dd MMMM yyyy", now));
}
}, now);
frag.show(ft, "DateDialogFragment"); }
更改
date.setText(String.valueOf(now.get(Calendar.DAY_OF_MONTH)+1)+"-"+String.valueOf(now.get(Calendar.MONTH))+"-"+String.valueOf(now.get(Calendar.YEAR)));
到
date.setText(DateFormat.format("dd MMMM yyyy", Calendar.getInstance()));
答案 2 :(得分:0)
public void showDialog()
{
FragmentTransaction ft = getFragmentManager().beginTransaction(); //get the fragment
frag = DateDialogFragment.newInstance(this, new DateDialogFragmentListener()
{
public void updateChangedDate(int year, int month, int day)
{
String dateFormate = "dd'" + getDayOfMonthSuffix(day) +"' MM yyyy";
DateFormat format = new SimpleDateFormat(dateFormate); // could be created elsewhere
now.set(year, month, day);
date.setText(format.format(now.getTime()));
now.set(year, month, day);
}
}, now);
frag.show(ft, "DateDialogFragment");
}
String getDayOfMonthSuffix(final int n) {
checkArgument(n >= 1 && n <= 31), "illegal day of month: " + n);
if (n >= 11 && n <= 13) {
return "th";
}
switch (n % 10) {
case 1: return "st";
case 2: return "nd";
case 3: return "rd";
default: return "th";
}
}
我从上面的链接
复制了getDayOfMonthSuffix函数