Java tutorial
//package com.java2s; /* * Copyright (C) 2016 venshine.cn@gmail.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class Main { public static final String DATE_FORMAT = "yyyyMMdd"; /** * Get date by year, month, day. * * @param year * @param month * @param day * @return */ public static String getDate(int year, int month, int day) { return "" + year + (month > 9 ? month : ("0" + month)) + (day > 9 ? day : ("0" + day)); } /** * Get date by time * * @param time * @return */ public static String getDate(long time) { SimpleDateFormat df = new SimpleDateFormat(DATE_FORMAT); Date now = new Date(time); return df.format(now); } /** * Get date by year, month * * @param year * @param month * @return */ public static String getDate(int year, int month) { String datetime = "" + year + (month > 9 ? month : ("0" + month)); String parrern = "yyyyMM"; SimpleDateFormat df = new SimpleDateFormat(parrern); try { Date date = df.parse(datetime); SimpleDateFormat df2 = new SimpleDateFormat(DATE_FORMAT); return df2.format(date); } catch (ParseException e) { e.printStackTrace(); } return ""; } }