/*
 * COPYRIGHT (c) 2018 All rights reserved by HANWHA LIFE.
 */
package kr.co.zumo.app.lifeplus.util;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Locale;

/**
 * Formatter
 * <pre>
 * </pre>
 *
 * @author 민효동
 * @version 1.0
 * @history 민효동   [2018. 9. 27.]   [최초 작성]
 * @since 2018. 9. 27.
 */
public class Formatter {
  /**
   * 날짜/시간 변환
   *
   * @param timeInMillis millisecond
   * @param pattern      yyyy-MM-dd HH:mm:ss
   * @return 2018-10-30 12:34:56
   */
  public static String format(long timeInMillis, String pattern) {
    return new SimpleDateFormat(pattern, Locale.getDefault()).format(timeInMillis);
  }

  /**
   * 시간 문자열을 다른 포맷으로 변경
   *
   * @param timeStr     2018-01-10 12:34:56
   * @param fromPattern yyyy-MM-dd HH:mm:ss
   * @param toPattern   yyyy/MM/dd
   * @return 2018-01-10
   */
  public static String format(String timeStr, String fromPattern, String toPattern) {
    long timeInMillis = dateStringToMillis(fromPattern, timeStr);
    return format(timeInMillis, toPattern);
  }

  /**
   * Date String 을 millisecond 로 변환
   *
   * @param pattern yyyy-MM-dd
   * @param dateStr 2016-10-21
   * @return millisecond
   */
  public static long dateStringToMillis(String pattern, String dateStr) {
    if (StringUtil.isEmpty(dateStr)) {
      return 0;
    }

    DateFormat format = new SimpleDateFormat(pattern, Locale.getDefault());
    try {
      return format.parse(dateStr).getTime();
    } catch (ParseException e) {
      e.printStackTrace();
      return 0;
    }
  }
}
