gpt4 book ai didi

android - 将日期和时间从日期选择器和时间时间选择器对话框存储到 MySQL

转载 作者:行者123 更新时间:2023-11-29 00:31:02 25 4
gpt4 key购买 nike

我正在创建一个应用程序,我希望客户端在其中从 DatePicker 选择日期和时间,并将它们以日期时间格式存储到 SQL 服务器。有任何想法吗?因为我使用了 SimpleDateFormat 但它不起作用。

最佳答案

实际上格式化日期和时间在 sql 中很重要。

首先,您必须考虑从日期选择器获取的日期格式(通常是我们向用户显示的格式):

常量::

public static final String DATE_FORMAT = "MM/dd/yyyy";
public static final String SQL_DATETIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
public static final String SQL_DATE_FORMAT = "yyyy-MM-dd";

SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT, Locale.US);
SimpleDateFormat rdf = new SimpleDateFormat(SQL_DATE_FORMAT,
Locale.US);
SimpleDateFormat tdf = new SimpleDateFormat(SQL_DATETIME_FORMAT,
Locale.US);

日期选择器::

public static class DatePickerFragment extends DialogFragment implements
DatePickerDialog.OnDateSetListener {

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {

final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);

Bundle data = this.getArguments();
if (data.getBoolean("isSelected")) {
year = data.getInt("year") + 1900;
month = data.getInt("month");
day = data.getInt("day");
}

return new DatePickerDialog(getActivity(), this, year, month, day);
}

public void onDateSet(DatePicker view, int year, int month, int day) {
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT, Locale.US);
@SuppressWarnings("deprecation")
String formatedDate = sdf.format(new Date(year - 1900, month, day));
((BaseActivity) getActivity()).mValuePickListener.onPickedValue(
formatedDate, DIALOG_DATE_PICKER);
}
}

现在,将这种格式转换成 mysql 接受的格式来存储日期和时间:

Date selectedDate = new Date();
if (!date.getText().toString().trim().equalsIgnoreCase("")) {
selectedDate = sdf.parse(date.getText().toString());
}
String sqlDate = rdf.format(selectedDate);

PS::您也可以使用时间戳(long)在数据库中存储时间

关于android - 将日期和时间从日期选择器和时间时间选择器对话框存储到 MySQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16522259/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com