Krish
Krish

Reputation: 304

Datepicker not properly working on a textbox

i am trying to print datepicker value in textbox,but it print 8-9-2013(MM-dd-yyyy)instead of print 9-9-2013. enter image description here

my MainActivity.java is

package com.example.datepicker;

import java.util.Calendar;
import java.util.Date;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import android.support.v4.app.NavUtils;

public class MainActivity extends Activity {
Button button;
DatePicker picker;
TextView text;
String mydate=java.text.DateFormat.getTimeInstance().format(Calendar.getInstance().getTime());
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text=(TextView)findViewById(R.id.textView1);
picker=(DatePicker)findViewById(R.id.datePicker1);
button=(Button)findViewById(R.id.button1);
datepicker();
}
private void datepicker() {
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
text.setText(getCurrentDate());
}
private CharSequence getCurrentDate() {
StringBuilder sb=new StringBuilder();
sb.append("Current Date  ").append(picker.getMonth()).append("-").append(picker.getDayOfMonth()).append("-").append(picker.getYear());
return sb;
}
});
}
}

Upvotes: 1

Views: 150

Answers (4)

laalto
laalto

Reputation: 152797

The months are zero-based so you'll need to add one to format it this way.

This is not very well documented, but going the other way, init() documentation states the month is zero-based. Also it's reasonable to assume there's a Calendar underneath and in it the months are also zero-based.

Upvotes: 4

Tarsem Singh
Tarsem Singh

Reputation: 14199

use this

sb.append("Current Date  ").append((picker.getMonth())+1).append("-").append(picker.getDayOfMonth()).append("-").append(picker.getYear());

Upvotes: 1

Harish Godara
Harish Godara

Reputation: 2386

Android Calander.MONTH returns zero-based index of month so you have to show Calander.MONTH + 1 here

Upvotes: 1

Daniel L.
Daniel L.

Reputation: 5140

Calendar.MONTH is ZERO based, ie January==0. Just add one to the month before displaying it: sb.append("CurrentDate").append(picker.getMonth() + 1).append("").append(picker.getDayOfMonth()).append("-").append(picker.getYear());

Upvotes: 1

Related Questions