I have Calendar value which is from Date Picker and I want to convert this value to String format "yyyy-MM-dd"
This is my Date Picker code. I save the selected values to startYear, startMonth and startDay.
ipDcEventStartDay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
DatePickerDialog dpd = new DatePickerDialog(DoubleCheckEventActivity.this, new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
startYear = year;
startMonth = month;
startDay = dayOfMonth;
ipDcEventStartDay.setText(startYear+ "-" + (startMonth+1) + "-" + startDay);
ipDcEventStartDay.setTextColor(Color.parseColor("#000000"));
}
}, today.get(Calendar.YEAR), today.get(Calendar.MONTH), today.get(Calendar.DATE));
dpd.show();
}
});
and then I tried to convert these values to String in this way. But the log result is 0002-12-31 not what I selected from Date Picker.
Calendar start = Calendar.getInstance();
start.set(startYear, startMonth, startDay);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date startDate = start.getTime(); // Convert to Date
String strStartDate = sdf.format(startDate); // Convert to String
Log.d("start", strStartDate); // this result is 0002-12-31
Never use Calendar. That terrible class was supplanted years ago by the modern java.time classes.
LocalDate
Instead, use LocalDate for a date-only value with no time-of-day and no offset or time zone.
LocalDate x = LocalDate.now() ;
String output = x.toString() ;
Build from parts.
LocalDate x = LocalDate.of( y , m , d ) ;
Get parts.
int y = x.getYear() ;
int m = x.getMonthValue() ;
int d = x.getDayOfMonth() ;
If your code goes like this; the log shows the date value before picking any dates. So you see the value for year: 0, month: 0 and day:0 (which is shown as 0002-12-31). (Note that the code inside onDateSet() method runs asynchronously, when the user picks a date.)
int startYear, startMonth, startDay;
Calendar today = GregorianCalendar.getInstance();
ipDcEventStartDay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
DatePickerDialog dpd = new DatePickerDialog(DoubleCheckEventActivity.this, new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
startYear = year;
startMonth = month;
startDay = dayOfMonth;
ipDcEventStartDay.setText(startYear+ "-" + (startMonth+1) + "-" + startDay);
ipDcEventStartDay.setTextColor(Color.parseColor("#000000"));
}
}, today.get(Calendar.YEAR), today.get(Calendar.MONTH), today.get(Calendar.DATE));
dpd.show();
}
});
// startYear, startMonth, startDay are not initialized yet and equal 0.
Calendar start = Calendar.getInstance();
start.set(startYear, startMonth, startDay);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date startDate = start.getTime(); // Convert to Date
String strStartDate = sdf.format(startDate); // Convert to String
Log.d("start", strStartDate); // this result is 0002-12-31
Instead; if you try to convert your Date to String "after the values are set" (Shown below) .You can see it will be correctly converted.
int startYear, startMonth, startDay;
Calendar today = GregorianCalendar.getInstance();
ipDcEventStartDay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
DatePickerDialog dpd = new DatePickerDialog(DoubleCheckEventActivity.this, new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
startYear = year;
startMonth = month;
startDay = dayOfMonth;
ipDcEventStartDay.setText(startYear+ "-" + (startMonth+1) + "-" + startDay);
ipDcEventStartDay.setTextColor(Color.parseColor("#000000"));
//************************************************************
//Now we have the picked values.
Calendar start = Calendar.getInstance();
start.set(startYear, startMonth, startDay);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date startDate = start.getTime(); // Convert to Date
String strStartDate = sdf.format(startDate); // Convert to String
Log.d("start", strStartDate); // this result is 0002-12-31
//************************************************************
}
}, today.get(Calendar.YEAR), today.get(Calendar.MONTH), today.get(Calendar.DATE));
dpd.show();
}
});
Let's see the simple code to convert Date to String
Basic
Date date = Calendar.getInstance().getTime();
DateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
String strDate = dateFormat.format(date);
System.out.println("Converted String: " + strDate);
Advanced
Date date = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
String strDate = formatter.format(date);
System.out.println("Date Format with MM/dd/yyyy : "+strDate);
formatter = new SimpleDateFormat("dd-M-yyyy hh:mm:ss");
strDate = formatter.format(date);
System.out.println("Date Format with dd-M-yyyy hh:mm:ss : "+strDate);
formatter = new SimpleDateFormat("dd MMMM yyyy");
strDate = formatter.format(date);
System.out.println("Date Format with dd MMMM yyyy : "+strDate);
formatter = new SimpleDateFormat("dd MMMM yyyy zzzz");
strDate = formatter.format(date);
System.out.println("Date Format with dd MMMM yyyy zzzz : "+strDate);
formatter = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z");
strDate = formatter.format(date);
System.out.println("Date Format with E, dd MMM yyyy HH:mm:ss z : "+strDate);
}
Related
I have created a DatePicker within my app. But the problem I am trying to overcome is how to take the picked date and store it in my database:
In my DB, the date field is set to TEXT
private int mYear, mMonth, mDay, mHour, mMinute;
#Override
public void onClick(View v) {
final Calendar calendar = Calendar.getInstance();
//Get the date
if (v == buttonDatePicker) {
mYear = calendar.get(Calendar.YEAR);
mMonth = calendar.get(Calendar.MONTH);
mDay = calendar.get(Calendar.DAY_OF_MONTH);
DatePickerDialog datePickerDialog = new DatePickerDialog(this,
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
etDate.setText(dayOfMonth + "-" + month + "-" + year);
mYear = year;
mMonth = month;
mDay = dayOfMonth;
}
}, mYear, mMonth, mDay);
datePickerDialog.show();
}
//Get the time
if (v == buttonTimePicker) {
mHour = calendar.get(Calendar.HOUR_OF_DAY);
mMinute = calendar.get(Calendar.MINUTE);
TimePickerDialog timePickerDialog = new TimePickerDialog(this,
new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
etTime.setText(hourOfDay + ":" + minute);
mHour = hourOfDay;
mMinute = minute;
}
}, mHour, mMinute, true);
timePickerDialog.show();
}
}
I tried to convert the picked Year etc from int to String but it does not seem to like it when I tried to cast it.
How I am trying to store it in my DB :
typedUpSmsMessage = smsMessage.getText().toString();
ContentValues cv = new ContentValues();
cv.put("textMessage", typedUpSmsMessage);
cv.put("dateToSendText",mYear + mMonth + mDay);
cv.put("gameID", gameID);
automateGameDB.insert("automateGames", null, cv);
But ofcourse since the date is in int, it just adds the numbers.
Need to convert them into a string, or a date format? (yyyy-mm-dd hh-mm-ss)?
Thanks
Since the field is Text you should use cv.put("dateToSendText", year + "-" + month + "-" + dayOfMonth) with 4 digit year and 2 digit month and dayOfMonth, because it is comparable and sortable.
Insert your date in database like
cv.put("dateToSendText",dayOfMonth + "-" + month + "-" + year)
or
cv.put("dateToSendText",etTime.gettext().tostring());
Really don't understand your requirement.
Will this code
String string = Integer.toString(int); or String.valueOf(int) or simply string+""
solve your problem?
I advise you to store Date as a timestamp in your database :
Calendar calendar = Calendar.getInstance()
calendar.set(year, month, day, hour, minute, second)
Long timestamp = calendar.getTimeInMillis() // Save timestamp in database
Use
inputDate = mYear +"-"+ mMonth +"-"+ mDay;
SimpleDateFormat src = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
SimpleDateFormat dest = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss", Locale.US);
Date date = null;
try {
date = src.parse(inputDate);
} catch (ParseException e) {
Log.d("Exception",e.getMessage());
}
String formattedDate = dest.format(date);
You can change dest Dateformat as u want...
Use 'TEXT' datatype in sqlite to store this date field
I need your help in getting the list of months and the years in String between two dates. The user will enter two dates in the String format of:
String date1 ="JAN-2015";
String date2 ="APR-2015";
So the result should be:
Jan-2015
FEB-2015
MAR-2015
I tried using the following code but it gave me wrong results:
List<Date> dates = new ArrayList<Date>();
String str_date ="JAN-2015";
String end_date ="APR-2015";
DateFormat formatter ;
formatter = new SimpleDateFormat("MMM-yyyy");
Date startDate = formatter.parse(str_date);
Date endDate = formatter.parse(end_date);
long endTime =endDate.getTime() ;
long curTime = startDate.getTime();
while (curTime <= endTime) {
dates.add(new Date(curTime));
curTime ++;
}
for(int i=0;i<dates.size();i++){
Date lDate =(Date)dates.get(i);
String ds = formatter.format(lDate);
System.out.println(ds);
}
Using the less code possible and basic java libraries and getting the result you asked for. So you can modify the date1 and date2 variables.
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class Main {
public static void main(String[] args) {
String date1 = "JAN-2015";
String date2 = "APR-2015";
DateFormat formater = new SimpleDateFormat("MMM-yyyy");
Calendar beginCalendar = Calendar.getInstance();
Calendar finishCalendar = Calendar.getInstance();
try {
beginCalendar.setTime(formater.parse(date1));
finishCalendar.setTime(formater.parse(date2));
} catch (ParseException e) {
e.printStackTrace();
}
while (beginCalendar.before(finishCalendar)) {
// add one month to date per loop
String date = formater.format(beginCalendar.getTime()).toUpperCase();
System.out.println(date);
beginCalendar.add(Calendar.MONTH, 1);
}
}
}
In case your Java version is < 8 you could use Calendar as follows:
private final static DateFormat formatter = new SimpleDateFormat("MMM-yyyy", Locale.ENGLISH);
public static void main(String[] args) throws ParseException {
Calendar startDate = stringToCalendar("Jan-2015");
Calendar endDate = stringToCalendar("Apr-2015");
while (startDate.before(endDate)) {
System.out.println(formatter.format(startDate.getTime()));
startDate.add(Calendar.MONTH, 1);
}
}
private static Calendar stringToCalendar(String string) throws ParseException {
Date date = formatter.parse(string);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar;
}
If you have a luxury of Java 8 then the code becomes more simple:
public static void main(String[] args) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM-yyyy", Locale.ENGLISH);
YearMonth startDate = YearMonth.parse("Jan-2015", formatter);
YearMonth endDate = YearMonth.parse("Apr-2015", formatter);
while(startDate.isBefore(endDate)) {
System.out.println(startDate.format(formatter));
startDate = startDate.plusMonths(1);
}
}
I want interval date. Whatever user enter date from date picker and from this date I want to get after one month date Suppose 1 Aug 2014 -> Output will be 1 September 2014.Can someone help me .Thanks to appreciate.
Hare is my Activity code
{
// Get current date by calender
final Calendar c = Calendar.getInstance();
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);
// Month is 0 based, just add 1
etReplacementDate.setText(new StringBuilder()
.append(month + 1).append("-").append(day).append("-")
.append(year).append(" "));
etReplacementDate.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
showDialog(DATE_OF_REPLACEMENT);
}
});
String fixedDate = etReplacementDate.getText().toString().trim();
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss aa");
Date convertedDate = new Date();
try
{
convertedDate = dateFormat.parse(fixedDate);
}
catch (ParseException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Date Consersion = " + convertedDate);
/****************ReplaceMent Date***************************************************/
cal2.add(Calendar.getInstance(convertedDate), 30);
Date date_30dayslater = cal2.getTime();
System.out.println("date_30dayslater : " + date_30dayslater);
/****************Interval Date***************************************************/
String _30daysLater_String = new SimpleDateFormat("yyyy-MM-dd").format(date_30dayslater);
etNextReplanishmentDate.setText(_30daysLater_String);
System.out.println("30 days later: " + _30daysLater_String);
System.out.println("______________________________________");
/****************Before Date***************************************************/
cal2.add(Calendar.DATE, -1);
Date beforDate = cal2.getTime();
String beforDate_String = new SimpleDateFormat("yyyy-MM-dd").format(beforDate);
System.out.println("beforDate_String: " + beforDate_String);
}
#Override
protected Dialog onCreateDialog(int id)
{
switch (id)
{
case DATE_OF_REPLACEMENT:return new DatePickerDialog(this, pickerListenerReplacement, year, month, day);
}
return null;
}
private DatePickerDialog.OnDateSetListener pickerListenerReplacement = new DatePickerDialog.OnDateSetListener() {
// when dialog box is closed, below method will be called.
#Override
public void onDateSet(DatePicker view, int selectedYear,
int selectedMonth, int selectedDay) {
year = selectedYear;
month = selectedMonth;
day = selectedDay;
// Show selected date
etReplacementDate.setText(new StringBuilder().append(month + 1)
.append("-").append(day).append("-").append(year)
.append(" "));
}
};
}
What you want to do is add() one Calendar.MONTH to a date that you've gotten and parsed, etc. so I won't go into that. I'll assume you are handling everything correctly up to the point where you'd like to get the same day, if possible, of the next month.
Part of your problem, as your comment suggests, is Calendar.getInstance() does not have an implementation that takes a Date. But more importantly you don't need it. You have a Date and a Calendar instance and it seems like you're changing c2 anyway so why not use Calendar's setTime() method like this?
// setting c2 with the convertedDate then adding a month
c2.setTime(convertedDate);
c2.add(Calendar.MONTH, 1);
// Simple example
public static void main(String...args) {
Date d = new Date();
Calendar c = Calendar.getInstance();
c.setTime(d);
System.out.println(c.getTime());
c.add(Calendar.MONTH, 1);
System.out.println(c.getTime());
}
try to use this.
Calendar c = Calendar.getInstance();
int month = c.get((Calendar.MONTH));
c.set(Calendar.MONTH, month + 1);
long time = c.getTimeInMillis();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String result = sdf.format(new Date(time1));
I have a code
String date = 05/09/13 10.55 PM;
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yy hh.mm a");
Date testDate = null;
testDate = sdf.parse(date);
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss a");
String newFormat = formatter.format(testDate);
System.out.println(".....Date..." + newFormat);
And this gives me output as
05/09/13 10:55:00 PM
What i actually need:
05/09/13 11:55:00 PM //i want to add an hour to the date I got
Use below code This will add 1 hour and print required result.
String date = "05/09/13 10.55 PM";
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yy hh.mm a");
Date testDate = null;
try {
testDate = sdf.parse(date);
// Add 1 hour logic
Calendar tmpCalendar = new GregorianCalendar();
tmpCalendar.setTime(testDate);
tmpCalendar.add(Calendar.HOUR_OF_DAY, 1);
testDate = tmpCalendar.getTime();
// Continue with your logic
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss a");
String newFormat = formatter.format(testDate);
System.out.println(".....Date..." + newFormat);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Output
.....Date...05/09/2013 11:55:00 PM
Date newDate = DateUtils.addHours(testDate, 1);
DateUtils.addHours
Edit:
Here u are:
String date = 05/09/13 10.55 PM;
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yy hh.mm a");
Date testDate = sdf.parse(date);
Date newDate = DateUtils.addHours(testDate, 1);
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss a");
String newFormat = formatter.format(newDate);
System.out.println(".....Date..." + newFormat);
I have written a function for adding time in a 24 hour format as given below
for (int i = 0; i < cursor.getCount(); i++) {
String RevisedTime="00:00";
// get hour and minute from time string
StringTokenizer st1 = new StringTokenizer(RevisedTime, ":");
int j = 0;
int[] val = new int[st1.countTokens()];
// iterate through tokens
while (st1.hasMoreTokens()) {
val[j] = Integer.parseInt(st1.nextToken());
j++;
}
// call time add method with current hour, minute and minutesToAdd,
// return added time as a string
String date = addTime(val[0], val[1], 15);
}
public String addTime(int hour, int minute, int minutesToAdd) {
Calendar calendar = new GregorianCalendar(1990, 1, 1, hour, minute);
calendar.add(Calendar.MINUTE, minutesToAdd);
SimpleDateFormat sdf = new SimpleDateFormat("kk:mm");
String date = sdf.format(calendar.getTime());
return date;
}
The problem is that while adding 15 minutes to 00:00 I am getting the output as 12.15....
I need to get it as 00:15......Pleas help me.....
You have to use 0-23 hour format, not 1-24.
Instead of SimpleDateFormat sdf = new SimpleDateFormat("kk:mm");
use SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
You just have to change a bit and it would work fine.
Replace
SimpleDateFormat sdf = new SimpleDateFormat("kk:mm");
By
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");