我尽力做研究并寻找教程,但仍然对此感到困惑。我的问题是,我希望显示类似于"分钟前的内容"基于我从json数据中获取的创建日期和时间。
当我从服务器获取日期和时间时,我想在livestatTimeAgo textview中显示它,但它显示错误,因为getTimeAgo方法是长格式的。所以我使用parseLong来更改我提取的数据,但仍然出错。有人可以给我提示如何将长数据显示为字符串值。
这是错误日志:
FATAL EXCEPTION: main
Process: com.baracode.eilsan, PID: 898
java.lang.NumberFormatException: For input string: "2017-08-25 09:20:54"
at java.lang.Long.parseLong(Long.java:443)
at java.lang.Long.parseLong(Long.java:485)
at com.baracode.eilsan.livestat.adapter.LivestatAdapter.onBindViewHolder(LivestatAdapter.java:49)
at com.baracode.eilsan.livestat.adapter.LivestatAdapter.onBindViewHolder(LivestatAdapter.java:29)
at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:6400)
at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:6433)
at android.support.v7.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:5377)
这是我的代码
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.baracode.eilsan.R;
import com.baracode.eilsan.model.LiveFeed;
import java.text.DateFormat;
import java.text.Format;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
/**
* Created by kille on 17/7/2017.
*/
public class LivestatAdapter extends RecyclerView.Adapter<LivestatAdapter.MyViewHolder> {
private final ArrayList<LiveFeed> livestatList;
private LiveFeed liveFeed;
public LivestatAdapter(ArrayList<LiveFeed> livestatList) {
this.livestatList = livestatList;
}
@Override
public LivestatAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_livestat, parent, false);
return new LivestatAdapter.MyViewHolder(itemView);
}
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
LiveFeed livestatModel = livestatList.get(position);
holder.livestatTimeAgo.setText(getTimeAgo(Long.parseLong(livestatModel.createdAt)));
holder.livestatOrganisationName.setText(livestatModel.beneficiaryName);
holder.livestatMoneyDonated.setText(livestatModel.amount);
holder.livestatDonorName.setText(livestatModel.donorName);
}
@Override
public int getItemCount() {
return livestatList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView livestatTimeAgo, livestatDonorName, livestatOrganisationName, livestatMoneyDonated;
public MyViewHolder(View view) {
super(view);
livestatTimeAgo = view.findViewById(R.id.livestat_time_ago);
livestatOrganisationName = view.findViewById(R.id.livestat_organisation_name);
livestatMoneyDonated = view.findViewById(R.id.livestat_money_donated);
livestatDonorName = view.findViewById(R.id.livestat_donor_name);
}
}
// private String ConvertTime(String time) {
//
// SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// SimpleDateFormat format1 = new SimpleDateFormat("hh:mm aa MM-dd");
// java.util.Date date = null;
//
// try {
// date = format.parse(time);
// } catch (ParseException e) {
// e.printStackTrace();
// }
//
// String convertedDate = format1.format(date);
//
// return convertedDate;
// }
public static String getTimeAgo(long timestamp) {
Calendar cal = Calendar.getInstance();
TimeZone tz = cal.getTimeZone();//get your local time zone.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd hh:mm ss");
sdf.setTimeZone(tz);//set time zone.
String localTime = sdf.format(new Date(timestamp * 1000));
Date date = new Date();
try {
date = sdf.parse(localTime);//get local date
} catch (ParseException e) {
e.printStackTrace();
}
if(date == null) {
return null;
}
long time = date.getTime();
Date curDate = currentDate();
long now = curDate.getTime();
if (time > now || time <= 0) {
return null;
}
int timeDIM = getTimeDistanceInMinutes(time);
String timeAgo = null;
if (timeDIM == 0) {
timeAgo = "less than a minute";
} else if (timeDIM == 1) {
return "1 minute";
} else if (timeDIM >= 2 && timeDIM <= 44) {
timeAgo = timeDIM + " minutes";
} else if (timeDIM >= 45 && timeDIM <= 89) {
timeAgo = "about an hour";
} else if (timeDIM >= 90 && timeDIM <= 1439) {
timeAgo = "about " + (Math.round(timeDIM / 60)) + " hours";
} else if (timeDIM >= 1440 && timeDIM <= 2519) {
timeAgo = "1 day";
} else if (timeDIM >= 2520 && timeDIM <= 43199) {
timeAgo = (Math.round(timeDIM / 1440)) + " days";
} else if (timeDIM >= 43200 && timeDIM <= 86399) {
timeAgo = "about a month";
} else if (timeDIM >= 86400 && timeDIM <= 525599) {
timeAgo = (Math.round(timeDIM / 43200)) + " months";
} else if (timeDIM >= 525600 && timeDIM <= 655199) {
timeAgo = "about a year";
} else if (timeDIM >= 655200 && timeDIM <= 914399) {
timeAgo = "over a year";
} else if (timeDIM >= 914400 && timeDIM <= 1051199) {
timeAgo = "almost 2 years";
} else {
timeAgo = "about " + (Math.round(timeDIM / 525600)) + " years";
}
return timeAgo + " ago";
}
public static Date currentDate() {
Calendar calendar = Calendar.getInstance();
return calendar.getTime();
}
private static int getTimeDistanceInMinutes(long time) {
long timeDistance = currentDate().getTime() - time;
return Math.round((Math.abs(timeDistance) / 1000) / 60);
}
}
这里是我的生活课......
public class LiveFeed {
@SerializedName("id")
public String id = "";
@SerializedName("ref_id")
public String refId = "";
@SerializedName("beneficiary_type")
public String beneficiaryType = "";
@SerializedName("beneficiary_name")
public String beneficiaryName = "";
@SerializedName("donor_name")
public String donorName = "";
@SerializedName("amount")
public String amount = "";
@SerializedName("description")
public String description = "";
@SerializedName("remark")
public String remark = "";
@SerializedName("status")
public String status = "";
@SerializedName("created_at")
public String createdAt = "";
@SerializedName("updated_at")
public String updatedAt = "";
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getRefId() {
return refId;
}
public void setRefId(String refId) {
this.refId = refId;
}
public String getBeneficiaryType() {
return beneficiaryType;
}
public void setBeneficiaryType(String beneficiaryType) {
this.beneficiaryType = beneficiaryType;
}
public String getBeneficiaryName() {
return beneficiaryName;
}
public void setBeneficiaryName(String beneficiaryName) {
this.beneficiaryName = beneficiaryName;
}
public String getDonorName() {
return donorName;
}
public void setDonorName(String donorName) {
this.donorName = donorName;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getCreatedAt() {
return createdAt;
}
public void setCreatedAt(String createdAt) {
this.createdAt = createdAt;
}
public String getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(String updatedAt) {
this.updatedAt = updatedAt;
}
}
所以这是我的问题的正确答案..关于如何获得时间的更新代码..对于任何想要推荐的人!谢谢
DateFormat getDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String fromDate = getDate.format(Calendar.getInstance().getTime());
String endDate = livestatModel.updatedAt; //here my jsondataName
long diff = 0;
try {
//Convert to Date
Date startDate = getDate.parse(fromDate);
Calendar c1 = Calendar.getInstance();
//Change to Calendar Date
c1.setTime(startDate);
//Convert to Date
Date endDate2 = getDate.parse(endDate);
Calendar c2 = Calendar.getInstance();
//Change to Calendar Date
c2.setTime(endDate2);
//get Time in milli seconds
long ms1 = c1.getTimeInMillis();
long ms2 = c2.getTimeInMillis();
//get difference in milli seconds
diff = ms1 - ms2;
if (diff < 0) {
holder.livestatTimeAgo.setText(" 0 day " + " 0 hour " + " 0 minute " + " 0 sec " + "left");
} else {
int diffInDays = (int) (diff / (1000 * 60 * 60 * 24));
int diffInHours = (int) ((diff / (1000 * 60 * 60)) % 24);
int diffInMinutes = (int) ((diff % (1000 * 60 * 60)) / (1000 * 60));
int diffInSec = (int) ((diff / 1000) % 60);
holder.livestatTimeAgo.setText(diffInDays + " days " + diffInHours + " hours " + diffInMinutes + " minutes " + diffInSec + " secs " + "Ago");
}
}catch (Exception e){}
答案 0 :(得分:1)
首先将您的字符串转换为日历:
#include <stdio.h>
struct employee
{
char name[20];
} emp = { .name = "John" };
int main(void)
{
printf("%s\n",emp.name);
return 0;
}
然后使用
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);
cal.setTime(sdf.parse("2017-08-25 09:20:54"));
这应该是诀窍。
修改强>
这是您想要做的一个可能的例子。我不知道计算是否正确但是有效。
long time = cal.getTimeInMillis();
答案 1 :(得分:0)
您在下一行中收到错误。
holder.livestatTimeAgo.setText(getTimeAgo(Long.parseLong(livestatModel.createdAt)));
由于错误为java.lang.NumberFormatException: For input string: "2017-08-25 09:20:54"
,因此livestatModel.createdAt
的含义非常重要
2017-08-25 09:20:54
更多是String值,无法解析为Long,因为它包含冒号,连字符和空格等语法。
<强>更新强>
要将日期字符串转换为long,您需要使用livestatModel.createdAt
解析SimpleDateFormat
(就像您在getTimeAgo
方法中所做的那样,但格式不同)。
以下是您如何实现这一目标。
long createdAtLong = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(livestatModel.createdAt).getTime();
holder.livestatTimeAgo.setText(getTimeAgo(createdAtLong));