Android Studio
[Android Studio] 글로벌 표준시(UTC)를 로컬의 시간으로 변경하기
dong_su
2024. 1. 8. 17:51
DB에서 가져온 createdAt 컬럼의 데이터는 글로벌 표준시(UTC)로 되어 있기 때문에
아래 코드와 같이 로컬의 시간으로 변경해야 한다.
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
SimpleDateFormat df = new SimpleDateFormat("yyyy년MM월dd일 HH시mm분ss초");
sf.setTimeZone(TimeZone.getTimeZone("UTC"));
df.setTimeZone(TimeZone.getDefault());
// 서버의 시간(글로벌 표준시)를 로컬의 시간으로 변환해야 한다.
try {
Date date = sf.parse(posting.createdAt);
String localTime = df.format(date);
holder.txtDate.setText(localTime);
} catch (ParseException e) {
throw new RuntimeException(e);
}
근데 아래 코드 4줄은 어뎁터의 onBindViewHolder()에 넣으면,
ArrayList 모든 요소마다 같은 작업을 계속 cpu가 수행하기 때문에
성능 개선을 위해 첫 1회만 실행하도록 생성자 함수와 전역변수로 뺀다.
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
SimpleDateFormat df = new SimpleDateFormat("yyyy년MM월dd일 HH시mm분ss초");
sf.setTimeZone(TimeZone.getTimeZone("UTC"));
df.setTimeZone(TimeZone.getDefault());
전체 코드
public class PostingAdapter extends RecyclerView.Adapter<PostingAdapter.ViewHolder> {
Context context;
ArrayList<Posting> postingArrayList;
SimpleDateFormat sf;
SimpleDateFormat df;
public PostingAdapter(Context context, ArrayList<Posting> postingArrayList) {
this.context = context;
this.postingArrayList = postingArrayList;
// 성능 개선을 위해 첫 1회만 실행하도록 생성자 안에다 넣는다.
sf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
df = new SimpleDateFormat("yyyy년MM월dd일 HH시mm분ss초");
sf.setTimeZone(TimeZone.getTimeZone("UTC"));
df.setTimeZone(TimeZone.getDefault());
}
@NonNull
@Override
public PostingAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.posting_row, parent, false);
return new PostingAdapter.ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
Posting posting = postingArrayList.get(position);
Glide.with(context).load(posting.imageUrl).into(holder.imgPhoto);
holder.txtContent.setText(posting.content);
holder.txtEmail.setText(posting.email);
// 서버의 시간(글로벌 표준시)를 로컬의 시간으로 변환해야 한다.
try {
Date date = sf.parse(posting.createdAt);
String localTime = df.format(date);
holder.txtDate.setText(localTime);
} catch (ParseException e) {
throw new RuntimeException(e);
}
// 좋아요 처리
if (posting.isFavorite == 0){
holder.imgLike.setImageResource(R.drawable.favorite_null);
} else {
holder.imgLike.setImageResource(R.drawable.baseline_favorite_24);
}
}
@Override
public int getItemCount() {
return postingArrayList.size();
}
// 아래는 생략