【问题标题】:how to fetch the date and time and save it in textfile android?如何获取日期和时间并将其保存在文本文件android中?
【发布时间】:2013-04-20 10:11:24
【问题描述】:

我每半小时获取一次 gps 位置并在 textview 中显示它,同时使用以下代码将 textview 中传递的值保存到 sdcard gpsdata.txt 文件,但在这里我必须保存它的时间和日期以及编号。


  • 现在我在 txt 文件中得到这样的 gps 位置:

13.01471695,80.1469223 13.01471695,
80.1469223 13.01471695,80.1469223
13.01471695,80.1469223

  • 但我需要这样:

1)13.01471695,80.1469223 时间:12 下午 30 点日期:2013 年 1 月 1 日
2)13.01471670,80.1469260 时间:12 下午 45 点日期:2013 年 1 月 1 日

public void appendData(String text)
{       
   File dataFile = new File(Environment.getExternalStorageDirectory() + "/SUNDTH/GpsData.txt");
   if (!dataFile.exists())
   {
      try
      {
         dataFile.createNewFile();
      } 
      catch (IOException e)
      {
         // TODO Auto-generated catch block
         e.printStackTrace();
      }
   }
   try
   {
      //BufferedWriter for performance, true to set append to file flag
      BufferedWriter buf = new BufferedWriter(new FileWriter(dataFile, true)); 
      buf.append(text);
      buf.newLine();
      buf.close();
   }
   catch (IOException e)
   {
      // TODO Auto-generated catch block
      e.printStackTrace();
   }
}

谢谢。

【问题讨论】:

    标签: android date time gps location


    【解决方案1】:

    buf.append(text);行前添加这行代码;

    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm dd/MM/yyyy");
    String currentDateandTime = sdf.format(new Date());
    text+=" "+currentDateandTime;
    

    【讨论】:

      【解决方案2】:
      SimpleDateFormat dateFormat = new SimpleDateFormat("d/M/yyyy");
      SimpleDateFormat timeFormat = new SimpleDateFormat("hh:mmz");
      

      这里是生成单个语句的代码,我假设你使用 Location 对象

      13.01471695,80.1469223 time:12 30pm date:1/1/2013
      
      Date locationDate = new Date(location.getTime());
      
      StringBuilder sb = new StringBuilder(location.getLatitude())
      .append(",")
      .append(location.getLongitude())
      .append("time:")
      .append(timeFormat.format(locationDate))
      .append(" date:")
      .append(dateFormat.format(locationDate));
      
      String locationDetail = sb.toString();
      

      【讨论】:

      • 如果可以的话,我可以对文件输出流应用同样的方法吗?请告诉我如何实现
      【解决方案3】:

      为什么不为此使用SQLiteDatabase,那么您可以简单地使用这样的东西来插入具有当前日期时间的记录:

      How to insert a SQLite record with a datetime set to 'now' in Android application?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-09-25
        相关资源
        最近更新 更多