【问题标题】:How to? Insert current date from Android into mySQL database using Retrofit2如何?使用 Retrofit2 将当前日期从 Android 插入 mySQL 数据库
【发布时间】:2019-10-12 06:22:41
【问题描述】:

尝试通过 Retrofit 将当前日期从 android 插入 mysql。日期在 mysql 数据库中显示为 0000-00-00。我已经阅读了关于这个主题的多个线程并尝试应用答案,但到目前为止我还没有成功。请参阅下面的代码 sn-ps 了解上下文。

PHP 代码:

<?php

include('conn.php');

$userId = $_POST['userId'];
$moodBefore = $_POST['moodBefore'];
$automaticThought = $_POST['automaticThought'];
$distortions = $_POST['distortions'];
$challengeThought = $_POST['challengeThought'];
$alternativeThought = $_POST['alternativeThought'];
$moodAfter = $_POST['moodAfter'];
$posted = $_POST['posted'];

$insert = "INSERT INTO Cbt ( userId, moodBefore,   automaticThought, distortions, challengeThought, alternativeThought, moodAfter, posted) VALUES
('$userId','$moodBefore', '$automaticThought', '$distortions', '$challengeThought', '$alternativeThought', '$moodAfter', '$posted')";

  $resultinsert = $conn -> query($insert);
              if(!$resultinsert){
                  echo $conn->error;
        }
 ?>

改造 API 代码:

public interface Api {

    @FormUrlEncoded
    @POST("insert.php")
    Call<ResponseBody> insertLog(
            @Field("userId") int userId,
            @Field("moodBefore") int moodBefore,
            @Field("automaticThought") String automaticThought,
            @Field("distortions") int distortions,
            @Field("challengeThought") String challengeThought,
            @Field("alternativeThought") String alternativeThought,
            @Field("moodAfter") int moodAfter,
            @Field("posted") String date
    );

JAVA 代码:

String posted = new SimpleDateFormat("ddMMyyyy").format(new Date());

case R.id.nextBtnMoodPage:
                if (hasSelected) {

                    Call<ResponseBody> call = RetrofitClient
                            .getInstance()
                            .getApi()
                            .insertLog(userId, moodBefore, automaticThoughtString, distortions, challengeThoughtString, alternativeThoughtString, moodAfter, posted);

                    call.enqueue(new Callback<ResponseBody>() {.....and so on

我希望日期插入成功且不显示 0000-00-00 如果我也可以将日期显示为 DD-MM-YYYY,那就更好了。

【问题讨论】:

    标签: java php android mysql retrofit2


    【解决方案1】:

    这在 Java 代码中有效,代码的所有其他部分保持不变

    private Date currentDate() {
        final Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, 0);
        return cal.getTime();
    }
    
    DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
    String posted = dateFormat.format(currentDate());
    

    【讨论】:

      猜你喜欢
      • 2012-10-18
      • 1970-01-01
      • 2015-07-31
      • 2013-11-23
      • 1970-01-01
      • 2016-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多