resolveInfoList = context.getPackageManager()
220 | .queryIntentActivities(resolveIntent, 0);
221 |
222 | ResolveInfo resolveinfo = resolveInfoList.iterator().next();
223 | if (resolveinfo != null) {
224 | String pkgName = resolveinfo.activityInfo.packageName;
225 | String className = resolveinfo.activityInfo.name;
226 |
227 | Intent intent = new Intent(Intent.ACTION_MAIN);
228 | intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
229 | intent.addCategory(Intent.CATEGORY_LAUNCHER);
230 |
231 | ComponentName cn = new ComponentName(pkgName, className);
232 | intent.setComponent(cn);
233 | context.startActivity(intent);
234 | }
235 | }
236 | }
237 |
--------------------------------------------------------------------------------
/app/src/main/java/wanglijun/vip/androidutils/utils/FileUtils.java:
--------------------------------------------------------------------------------
1 | package wanglijun.vip.androidutils.utils;
2 |
3 | import java.io.BufferedReader;
4 | import java.io.File;
5 | import java.io.FileInputStream;
6 | import java.io.FileNotFoundException;
7 | import java.io.FileOutputStream;
8 | import java.io.FileWriter;
9 | import java.io.IOException;
10 | import java.io.InputStream;
11 | import java.io.InputStreamReader;
12 | import java.io.OutputStream;
13 |
14 | /**
15 | * @author: wlj
16 | * @Date: 2017-03-28
17 | * @email: wanglijundev@gmail.com
18 | * @desc: 文件工具类
19 | */
20 | public class FileUtils {
21 |
22 | public final static String FILE_SUFFIX_SEPARATOR = ".";
23 |
24 | /**
25 | * Read file
26 | *
27 | * @param filePath
28 | * @param charsetName
29 | * @return
30 | */
31 | public static StringBuilder readFile(String filePath, String charsetName) {
32 | File file = new File(filePath);
33 | StringBuilder fileContent = new StringBuilder("");
34 | if (!file.isFile()) {
35 | return null;
36 | }
37 |
38 | BufferedReader reader = null;
39 | try {
40 | InputStreamReader is = new InputStreamReader(new FileInputStream(file), charsetName);
41 | reader = new BufferedReader(is);
42 | String line = null;
43 | while ((line = reader.readLine()) != null) {
44 | if (!"".equals(fileContent.toString())) {
45 | fileContent.append("\r\n");
46 | }
47 | fileContent.append(line);
48 | }
49 | return fileContent;
50 | } catch (IOException e) {
51 | throw new RuntimeException("IOException", e);
52 | } finally {
53 | IOUtils.close(reader);
54 | }
55 | }
56 |
57 | /**
58 | * Write file
59 | *
60 | * @param filePath
61 | * @param content
62 | * @param append
63 | * @return
64 | */
65 | public static boolean writeFile(String filePath, String content, boolean append) {
66 | if (StringUtils.isEmpty(content)) {
67 | return false;
68 | }
69 | FileWriter fileWriter = null;
70 | try {
71 | makeDirs(filePath);
72 | fileWriter = new FileWriter(filePath, append);
73 | fileWriter.write(content);
74 | return true;
75 | } catch (IOException e) {
76 | throw new RuntimeException("IOException occurred. ", e);
77 | } finally {
78 | IOUtils.close(fileWriter);
79 | }
80 | }
81 |
82 | /**
83 | * write file, the string will be written to the begin of the file
84 | *
85 | * @param filePath
86 | * @param content
87 | * @return
88 | */
89 | public static boolean writeFile(String filePath, String content) {
90 | return writeFile(filePath, content, false);
91 | }
92 |
93 | /**
94 | * Write file
95 | *
96 | * @param filePath
97 | * @param is
98 | * @return
99 | */
100 | public static boolean writeFile(String filePath, InputStream is) {
101 | return writeFile(filePath, is, false);
102 | }
103 |
104 | /**
105 | * Write file
106 | *
107 | * @param filePath
108 | * @param is
109 | * @param append
110 | * @return
111 | */
112 | public static boolean writeFile(String filePath, InputStream is, boolean append) {
113 | return writeFile(filePath != null ? new File(filePath) : null, is, append);
114 | }
115 |
116 | /**
117 | * Write file
118 | *
119 | * @param file
120 | * @param is
121 | * @return
122 | */
123 | public static boolean writeFile(File file, InputStream is) {
124 | return writeFile(file, is, false);
125 | }
126 |
127 | /**
128 | * Write file
129 | *
130 | * @param file
131 | * @param is
132 | * @param append
133 | * @return
134 | */
135 | public static boolean writeFile(File file, InputStream is, boolean append) {
136 | OutputStream o = null;
137 | try {
138 | makeDirs(file.getAbsolutePath());
139 | o = new FileOutputStream(file, append);
140 | byte[] data = new byte[1024];
141 | int length = -1;
142 | while ((length = is.read(data)) != -1) {
143 | o.write(data, 0, length);
144 | }
145 | o.flush();
146 | return true;
147 | } catch (FileNotFoundException e) {
148 | throw new RuntimeException("FileNotFoundException", e);
149 | } catch (IOException e) {
150 | throw new RuntimeException("IOException", e);
151 | } finally {
152 | IOUtils.close(o);
153 | IOUtils.close(is);
154 | }
155 | }
156 |
157 | /**
158 | * Move file
159 | *
160 | * @param srcFilePath
161 | * @param destFilePath
162 | */
163 | public static void moveFile(String srcFilePath, String destFilePath) throws FileNotFoundException {
164 | if (StringUtils.isEmpty(srcFilePath) || StringUtils.isEmpty(destFilePath)) {
165 | throw new RuntimeException("Both srcFilePath and destFilePath cannot be null.");
166 | }
167 | moveFile(new File(srcFilePath), new File(destFilePath));
168 | }
169 |
170 | /**
171 | * Move file
172 | *
173 | * @param srcFile
174 | * @param destFile
175 | */
176 | public static void moveFile(File srcFile, File destFile) throws FileNotFoundException {
177 | boolean rename = srcFile.renameTo(destFile);
178 | if (!rename) {
179 | copyFile(srcFile.getAbsolutePath(), destFile.getAbsolutePath());
180 | deleteFile(srcFile.getAbsolutePath());
181 | }
182 | }
183 |
184 | /**
185 | * Copy file
186 | *
187 | * @param srcFilePath
188 | * @param destFilePath
189 | * @return
190 | * @throws FileNotFoundException
191 | */
192 | public static boolean copyFile(String srcFilePath, String destFilePath) throws FileNotFoundException {
193 | InputStream inputStream = new FileInputStream(srcFilePath);
194 | return writeFile(destFilePath, inputStream);
195 | }
196 |
197 | /**
198 | * rename file
199 | *
200 | * @param file
201 | * @param newFileName
202 | * @return
203 | */
204 | public static boolean renameFile(File file, String newFileName) {
205 | File newFile = null;
206 | if (file.isDirectory()) {
207 | newFile = new File(file.getParentFile(), newFileName);
208 | } else {
209 | String temp = newFileName
210 | + file.getName().substring(
211 | file.getName().lastIndexOf('.'));
212 | newFile = new File(file.getParentFile(), temp);
213 | }
214 | if (file.renameTo(newFile)) {
215 | return true;
216 | }
217 | return false;
218 | }
219 |
220 | /**
221 | * Get file name without suffix
222 | *
223 | * @param filePath
224 | * @return
225 | */
226 | public static String getFileNameWithoutSuffix(String filePath) {
227 | if (StringUtils.isEmpty(filePath)) {
228 | return filePath;
229 | }
230 | int suffix = filePath.lastIndexOf(FILE_SUFFIX_SEPARATOR);
231 | int fp = filePath.lastIndexOf(File.separator);
232 | if (fp == -1) {
233 | return (suffix == -1 ? filePath : filePath.substring(0, suffix));
234 | }
235 | if (suffix == -1) {
236 | return filePath.substring(fp + 1);
237 | }
238 | return (fp < suffix ? filePath.substring(fp + 1, suffix) : filePath.substring(fp + 1));
239 | }
240 |
241 | /**
242 | * Get file name
243 | *
244 | * @param filePath
245 | * @return
246 | */
247 | public static String getFileName(String filePath) {
248 | if (StringUtils.isEmpty(filePath)) {
249 | return filePath;
250 | }
251 | int fp = filePath.lastIndexOf(File.separator);
252 | return (fp == -1) ? filePath : filePath.substring(fp + 1);
253 | }
254 |
255 | /**
256 | * Get folder name
257 | *
258 | * @param filePath
259 | * @return
260 | */
261 | public static String getFolderName(String filePath) {
262 | if (StringUtils.isEmpty(filePath)) {
263 | return filePath;
264 | }
265 | int fp = filePath.lastIndexOf(File.separator);
266 | return (fp == -1) ? "" : filePath.substring(0, fp);
267 | }
268 |
269 | /**
270 | * Get suffix of file
271 | *
272 | * @param filePath
273 | * @return
274 | */
275 | public static String getFileSuffix(String filePath) {
276 | if (StringUtils.isEmpty(filePath)) {
277 | return filePath;
278 | }
279 | int suffix = filePath.lastIndexOf(FILE_SUFFIX_SEPARATOR);
280 | int fp = filePath.lastIndexOf(File.separator);
281 | if (suffix == -1) {
282 | return "";
283 | }
284 | return (fp >= suffix) ? "" : filePath.substring(suffix + 1);
285 | }
286 |
287 | /**
288 | * Create the directory
289 | *
290 | * @param filePath
291 | * @return
292 | */
293 | public static boolean makeDirs(String filePath) {
294 | String folderName = getFolderName(filePath);
295 | if (StringUtils.isEmpty(folderName)) {
296 | return false;
297 | }
298 | File folder = new File(folderName);
299 | return (folder.exists() && folder.isDirectory()) || folder.mkdirs();
300 | }
301 |
302 | /**
303 | * Judge whether a file is exist
304 | *
305 | * @param filePath
306 | * @return
307 | */
308 | public static boolean isFileExist(String filePath) {
309 | if (StringUtils.isEmpty(filePath)) {
310 | return false;
311 | }
312 | File file = new File(filePath);
313 | return (file.exists() && file.isFile());
314 | }
315 |
316 | /**
317 | * Judge whether a folder is exist
318 | *
319 | * @param directoryPath
320 | * @return
321 | */
322 | public static boolean isFolderExist(String directoryPath) {
323 | if (StringUtils.isEmpty(directoryPath)) {
324 | return false;
325 | }
326 | File dire = new File(directoryPath);
327 | return (dire.exists() && dire.isDirectory());
328 | }
329 |
330 | /**
331 | * Delete file or folder
332 | *
333 | * @param path
334 | * @return
335 | */
336 | public static boolean deleteFile(String path) {
337 | if (StringUtils.isEmpty(path)) {
338 | return true;
339 | }
340 |
341 | File file = new File(path);
342 | if (!file.exists()) {
343 | return true;
344 | }
345 | if (file.isFile()) {
346 | return file.delete();
347 | }
348 | if (!file.isDirectory()) {
349 | return false;
350 | }
351 | if (file.isDirectory()) {
352 | for (File f : file.listFiles()) {
353 | if (f.isFile()) {
354 | f.delete();
355 | } else if (f.isDirectory()) {
356 | deleteFile(f.getAbsolutePath());
357 | }
358 | }
359 | }
360 | return file.delete();
361 | }
362 |
363 | /**
364 | * Delete file or folder
365 | *
366 | * @param file
367 | * @return
368 | */
369 | public static boolean deleteFile(File file) {
370 | if (!file.exists()) {
371 | return true;
372 | }
373 | if (file.isFile()) {
374 | return file.delete();
375 | }
376 | if (!file.isDirectory()) {
377 | return false;
378 | }
379 | file.isDirectory();
380 | File[] childFile = file.listFiles();
381 | if (childFile == null || childFile.length == 0) {
382 | return file.delete();
383 | }
384 | for (File f : childFile) {
385 | deleteFile(f);
386 | }
387 | return file.delete();
388 | }
389 |
390 | /**
391 | * Get file size
392 | *
393 | * @param path
394 | * @return
395 | */
396 | public static long getFileSize(String path) {
397 | if (StringUtils.isEmpty(path)) {
398 | return -1;
399 | }
400 | File file = new File(path);
401 | return (file.exists() && file.isFile() ? file.length() : -1);
402 | }
403 |
404 | /**
405 | * Get folder size
406 | *
407 | * @param file
408 | * @return
409 | * @throws Exception
410 | */
411 | public static long getFolderSize(File file) throws Exception {
412 | long size = 0;
413 | try {
414 | File[] fileList = file.listFiles();
415 | for (int i = 0; i < fileList.length; i++) {
416 | if (fileList[i].isDirectory()) {
417 | size = size + getFolderSize(fileList[i]);
418 | } else {
419 | size = size + fileList[i].length();
420 | }
421 | }
422 | } catch (Exception e) {
423 | e.printStackTrace();
424 | }
425 | return size;
426 | }
427 | }
428 |
--------------------------------------------------------------------------------
/app/src/main/java/wanglijun/vip/androidutils/utils/DeviceUtils.java:
--------------------------------------------------------------------------------
1 | package wanglijun.vip.androidutils.utils;
2 |
3 | import android.Manifest;
4 | import android.annotation.SuppressLint;
5 | import android.app.Activity;
6 | import android.bluetooth.BluetoothAdapter;
7 | import android.content.Context;
8 | import android.content.Intent;
9 | import android.media.AudioManager;
10 | import android.os.Build;
11 | import android.provider.Settings;
12 | import android.telephony.TelephonyManager;
13 | import android.view.Window;
14 | import android.view.WindowManager;
15 |
16 | import java.util.UUID;
17 |
18 | import androidx.annotation.RequiresPermission;
19 |
20 | /**
21 | * @author wlj
22 | * @date 2017/3/29
23 | * @email wanglijundev@gmail.com
24 | * @packagename wanglijun.vip.androidutils.utils
25 | * @desc: 获取设备信息
26 | */
27 |
28 | public class DeviceUtils {
29 | /**
30 | * 获取UUID
31 | * @param context
32 | * @return
33 | */
34 | @SuppressLint({"MissingPermission", "HardwareIds"})
35 | public static String getUUID(Context context) {
36 | final TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
37 |
38 | final String tmDevice, tmSerial, tmPhone, androidId;
39 | tmDevice = "" + tm.getDeviceId();
40 | tmSerial = "" + tm.getSimSerialNumber();
41 | androidId = "" + Settings.Secure.getString(context.getContentResolver(),
42 | Settings.Secure.ANDROID_ID);
43 |
44 | UUID deviceUuid = new UUID(androidId.hashCode(), ((long) tmDevice.hashCode() << 32) | tmSerial.hashCode());
45 |
46 | return deviceUuid.toString();
47 | }
48 |
49 | /**
50 | * Get screen brightness mode,must declare the
51 | * 获取屏幕亮度模式,必须声明
52 | * {@link Manifest.permission#WRITE_SETTINGS} permission in its manifest.
53 | *
54 | * @param context
55 | * @return
56 | */
57 | public static int getScreenBrightnessMode(Context context) {
58 | return Settings.System.getInt(context.getContentResolver(),
59 | Settings.System.SCREEN_BRIGHTNESS_MODE,
60 | Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
61 | }
62 |
63 | /**
64 | * Judge screen brightness mode is auto mode,must declare the
65 | * 判断屏幕亮度模式为自动模式,必须声明
66 | * {@link Manifest.permission#WRITE_SETTINGS} permission in its manifest.
67 | *
68 | * @param context
69 | * @return true:auto;false: manual;default:true
70 | */
71 | public static boolean isScreenBrightnessModeAuto(Context context) {
72 | return getScreenBrightnessMode(context) == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC;
73 | }
74 |
75 | /**
76 | * Set screen brightness mode,must declare the
77 | * 设置屏幕亮度模式,必须声明
78 | * {@link Manifest.permission#WRITE_SETTINGS} permission in its manifest.
79 | *
80 | * @param context
81 | * @param auto
82 | * @return
83 | */
84 | public static boolean setScreenBrightnessMode(Context context, boolean auto) {
85 | boolean result = true;
86 | if (isScreenBrightnessModeAuto(context) != auto) {
87 | result = Settings.System.putInt(context.getContentResolver(),
88 | Settings.System.SCREEN_BRIGHTNESS_MODE,
89 | auto ? Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC
90 | : Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
91 | }
92 | return result;
93 | }
94 |
95 | /**
96 | * Get screen brightness, must declare the
97 | * 获得屏幕亮度,必须声明
98 | * {@link Manifest.permission#WRITE_SETTINGS} permission in its manifest.
99 | *
100 | * @param context
101 | * @return brightness:0-255; default:255
102 | */
103 | public static int getScreenBrightness(Context context) {
104 | return Settings.System.getInt(context.getContentResolver(),
105 | Settings.System.SCREEN_BRIGHTNESS, 255);
106 | }
107 |
108 | /**
109 | * Set screen brightness, cannot change window brightness.must declare the
110 | * 屏幕亮度设置
111 | * {@link Manifest.permission#WRITE_SETTINGS} permission in its manifest.
112 | *
113 | * @param context
114 | * @param screenBrightness 0-255
115 | * @return
116 | */
117 | public static boolean setScreenBrightness(Context context,
118 | int screenBrightness) {
119 | int brightness = screenBrightness;
120 | if (screenBrightness < 1) {
121 | brightness = 1;
122 | } else if (screenBrightness > 255) {
123 | brightness = screenBrightness % 255;
124 | if (brightness == 0) {
125 | brightness = 255;
126 | }
127 | }
128 | boolean result = Settings.System.putInt(context.getContentResolver(),
129 | Settings.System.SCREEN_BRIGHTNESS, brightness);
130 | return result;
131 | }
132 |
133 | /**
134 | * Set window brightness, cannot change system brightness.
135 | * 设置窗口亮度,不能改变系统亮度
136 | *
137 | * @param activity
138 | * @param screenBrightness 0-255
139 | */
140 | public static void setWindowBrightness(Activity activity,
141 | float screenBrightness) {
142 | float brightness = screenBrightness;
143 | if (screenBrightness < 1) {
144 | brightness = 1;
145 | } else if (screenBrightness > 255) {
146 | brightness = screenBrightness % 255;
147 | if (brightness == 0) {
148 | brightness = 255;
149 | }
150 | }
151 | Window window = activity.getWindow();
152 | WindowManager.LayoutParams localLayoutParams = window.getAttributes();
153 | localLayoutParams.screenBrightness = brightness / 255.0f;
154 | window.setAttributes(localLayoutParams);
155 | }
156 |
157 | /**
158 | * Set screen brightness and change system brightness, must declare the
159 | * 设置屏幕亮度并改变系统亮度,必须声明
160 | * {@link Manifest.permission#WRITE_SETTINGS} permission in its manifest.
161 | *
162 | * @param activity
163 | * @param screenBrightness 0-255
164 | * @return
165 | */
166 | public static boolean setScreenBrightnessAndApply(Activity activity,
167 | int screenBrightness) {
168 | boolean result = setScreenBrightness(activity, screenBrightness);
169 | if (result) {
170 | setWindowBrightness(activity, screenBrightness);
171 | }
172 | return result;
173 | }
174 |
175 | /**
176 | * Get screen dormant time, must declare the
177 | * 获得屏幕休眠时间,必须声明
178 | * {@link Manifest.permission#WRITE_SETTINGS} permission in its manifest.
179 | *
180 | * @param context
181 | * @return dormantTime:ms, default:30s
182 | */
183 | public static int getScreenDormantTime(Context context) {
184 | return Settings.System.getInt(context.getContentResolver(),
185 | Settings.System.SCREEN_OFF_TIMEOUT, 30000);
186 | }
187 |
188 | /**
189 | * Set screen dormant time by millis, must declare the
190 | * 屏幕休眠时间等信息,必须申报
191 | * {@link Manifest.permission#WRITE_SETTINGS} permission in its manifest.
192 | *
193 | * @param context
194 | * @return
195 | */
196 | public static boolean setScreenDormantTime(Context context, int millis) {
197 | return Settings.System.putInt(context.getContentResolver(),
198 | Settings.System.SCREEN_OFF_TIMEOUT, millis);
199 | }
200 |
201 | /**
202 | * Get airplane mode, must declare the
203 | * 获取飞行模式,必须申报
204 | * {@link Manifest.permission#WRITE_APN_SETTINGS} permission in its manifest.
205 | *
206 | * @param context
207 | * @return 1:open, 0:close, default:close
208 | */
209 | public static int getAirplaneMode(Context context) {
210 | if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
211 | return Settings.System.getInt(context.getContentResolver(),
212 | Settings.System.AIRPLANE_MODE_ON, 0);
213 | } else {
214 | return Settings.Global.getInt(context.getContentResolver(),
215 | Settings.Global.AIRPLANE_MODE_ON, 0);
216 | }
217 | }
218 |
219 | /**
220 | * Judge whether airplane is open, must declare the
221 | * 判断飞行模式是否打开,必须声明
222 | * {@link Manifest.permission#WRITE_APN_SETTINGS} permission in its manifest.
223 | *
224 | * @param context
225 | * @return true:open, false:close, default:close
226 | */
227 | public static boolean isAirplaneModeOpen(Context context) {
228 | return getAirplaneMode(context) == 1;
229 | }
230 |
231 | /**
232 | * Set airplane mode, must declare the
233 | * 设置飞行模式,必须声明
234 | * {@link Manifest.permission#WRITE_APN_SETTINGS} permission in its manifest.
235 | *
236 | * @param context
237 | * @param enable
238 | * @return
239 | */
240 | public static boolean setAirplaneMode(Context context, boolean enable) {
241 | boolean result = true;
242 | if (isAirplaneModeOpen(context) != enable) {
243 | if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
244 | result = Settings.System.putInt(context.getContentResolver(),
245 | Settings.System.AIRPLANE_MODE_ON, enable ? 1 : 0);
246 | } else {
247 | result = Settings.Global.putInt(context.getContentResolver(),
248 | Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
249 | }
250 | context.sendBroadcast(new Intent(
251 | Intent.ACTION_AIRPLANE_MODE_CHANGED));
252 | }
253 | return result;
254 | }
255 |
256 | /**
257 | * Get bluetooth state
258 | * 获取蓝牙状态
259 | *
260 | * @return STATE_OFF, STATE_TURNING_OFF, STATE_ON, STATE_TURNING_ON, NONE
261 | * @throws Exception
262 | */
263 | @RequiresPermission(Manifest.permission.BLUETOOTH)
264 | public static Integer getBluetoothState() {
265 | BluetoothAdapter bluetoothAdapter = BluetoothAdapter
266 | .getDefaultAdapter();
267 | if (bluetoothAdapter == null) {
268 | return null;
269 | } else {
270 | return bluetoothAdapter.getState();
271 | }
272 | }
273 |
274 | /**
275 | * Judge bluetooth is open
276 | * 判断蓝牙是否打开
277 | *
278 | * @return true:open, false:close.
279 | */
280 | public static boolean isBluetoothOpen() {
281 | @SuppressLint("MissingPermission") Integer bluetoothStateCode = getBluetoothState();
282 | if (bluetoothStateCode == null) {
283 | return false;
284 | }
285 | return bluetoothStateCode == BluetoothAdapter.STATE_ON
286 | || bluetoothStateCode == BluetoothAdapter.STATE_TURNING_ON;
287 | }
288 |
289 | /**
290 | * Set bluetooth
291 | * 设置蓝牙
292 | *
293 | * @param enable
294 | */
295 | @RequiresPermission(Manifest.permission.BLUETOOTH_ADMIN)
296 | public static void setBluetooth(boolean enable) throws Exception {
297 | if (isBluetoothOpen() != enable) {
298 | if (enable) {
299 | BluetoothAdapter.getDefaultAdapter().enable();
300 | } else {
301 | BluetoothAdapter.getDefaultAdapter().disable();
302 | }
303 | }
304 | }
305 |
306 | /**
307 | * Get media volume
308 | * 获取音量
309 | *
310 | * @param context
311 | * @return volume:0-15
312 | */
313 | public static int getMediaVolume(Context context) {
314 | return ((AudioManager) context.getSystemService(Context.AUDIO_SERVICE)).getStreamVolume(AudioManager
315 | .STREAM_MUSIC);
316 | }
317 |
318 | /**
319 | * Set media volume
320 | *设置音量
321 | *
322 | * @param context
323 | * @return volume:0-15
324 | */
325 | public static void setMediaVolume(Context context, int mediaVloume) {
326 | if (mediaVloume < 0) {
327 | mediaVloume = 0;
328 | } else if (mediaVloume > 15) {
329 | mediaVloume = mediaVloume % 15;
330 | if (mediaVloume == 0) {
331 | mediaVloume = 15;
332 | }
333 | }
334 | ((AudioManager) context.getSystemService(Context.AUDIO_SERVICE)).setStreamVolume(AudioManager.STREAM_MUSIC,
335 | mediaVloume, AudioManager.FLAG_PLAY_SOUND | AudioManager.FLAG_SHOW_UI);
336 | }
337 |
338 | /**
339 | * Get ring volume
340 | * 获取铃声音量
341 | *
342 | * @param context
343 | * @return volume:0-7
344 | */
345 | public static int getRingVolume(Context context) {
346 | return ((AudioManager) context.getSystemService(Context.AUDIO_SERVICE)).getStreamVolume(AudioManager
347 | .STREAM_RING);
348 | }
349 |
350 | /**
351 | * Set ring volume
352 | * 设置铃声音量
353 | *
354 | * @param context
355 | * @return volume:0-7
356 | */
357 | public static void setRingVolume(Context context, int ringVloume) {
358 | if (ringVloume < 0) {
359 | ringVloume = 0;
360 | } else if (ringVloume > 7) {
361 | ringVloume = ringVloume % 7;
362 | if (ringVloume == 0) {
363 | ringVloume = 7;
364 | }
365 | }
366 | ((AudioManager) context.getSystemService(Context.AUDIO_SERVICE)).setStreamVolume(AudioManager.STREAM_RING,
367 | ringVloume, AudioManager.FLAG_PLAY_SOUND);
368 | }
369 | }
370 |
--------------------------------------------------------------------------------
/app/src/main/java/wanglijun/vip/androidutils/utils/TimeUtils.java:
--------------------------------------------------------------------------------
1 | package wanglijun.vip.androidutils.utils;
2 |
3 | import java.text.ParseException;
4 | import java.text.SimpleDateFormat;
5 | import java.util.Calendar;
6 | import java.util.Date;
7 | import java.util.Locale;
8 | import java.util.TimeZone;
9 |
10 | /**
11 | * 时间相关
12 | *
13 | * @author wlj
14 | */
15 | public class TimeUtils {
16 |
17 | private TimeUtils() {
18 | throw new UnsupportedOperationException("u can't fuck me...");
19 | }
20 |
21 | /**
22 | * 在工具类中经常使用到工具类的格式化描述,这个主要是一个日期的操作类,所以日志格式主要使用 SimpleDateFormat的定义格式.
23 | * 格式的意义如下: 日期和时间模式
24 | * 日期和时间格式由日期和时间模式字符串指定。在日期和时间模式字符串中,未加引号的字母 'A' 到 'Z' 和 'a' 到 'z'
25 | * 被解释为模式字母,用来表示日期或时间字符串元素。文本可以使用单引号 (') 引起来,以免进行解释。"''"
26 | * 表示单引号。所有其他字符均不解释;只是在格式化时将它们简单复制到输出字符串,或者在分析时与输入字符串进行匹配。
27 | *
28 | * 定义了以下模式字母(所有其他字符 'A' 到 'Z' 和 'a' 到 'z' 都被保留):
29 | *
31 | *
32 | * | 字母 |
33 | * 日期或时间元素 |
34 | * 表示 |
35 | * 示例 |
36 | *
37 | *
38 | * G |
39 | * Era 标志符 |
40 | * Text |
41 | * AD |
42 | *
43 | *
44 | * y |
45 | * 年 |
46 | * Year |
47 | * 1996; 96 |
48 | *
49 | *
50 | * M |
51 | * 年中的月份 |
52 | * Month |
53 | * July; Jul; 07 |
54 | *
55 | *
56 | * w |
57 | * 年中的周数 |
58 | * Number |
59 | * 27 |
60 | *
61 | *
62 | * W |
63 | * 月份中的周数 |
64 | * Number |
65 | * 2 |
66 | *
67 | *
68 | * D |
69 | * 年中的天数 |
70 | * Number |
71 | * 189 |
72 | *
73 | *
74 | * d |
75 | * 月份中的天数 |
76 | * Number |
77 | * 10 |
78 | *
79 | *
80 | * F |
81 | * 月份中的星期 |
82 | * Number |
83 | * 2 |
84 | *
85 | *
86 | * E |
87 | * 星期中的天数 |
88 | * Text |
89 | * Tuesday; Tue |
90 | *
91 | *
92 | * a |
93 | * Am/pm 标记 |
94 | * Text |
95 | * PM |
96 | *
97 | *
98 | * H |
99 | * 一天中的小时数(0-23) |
100 | * Number |
101 | * 0 |
102 | *
103 | *
104 | * k |
105 | * 一天中的小时数(1-24) |
106 | * Number |
107 | * 24 |
108 | *
109 | *
110 | * K |
111 | * am/pm 中的小时数(0-11) |
112 | * Number |
113 | * 0 |
114 | *
115 | *
116 | * h |
117 | * am/pm 中的小时数(1-12) |
118 | * Number |
119 | * 12 |
120 | *
121 | *
122 | * m |
123 | * 小时中的分钟数 |
124 | * Number |
125 | * 30 |
126 | *
127 | *
128 | * s |
129 | * 分钟中的秒数 |
130 | * Number |
131 | * 55 |
132 | *
133 | *
134 | * S |
135 | * 毫秒数 |
136 | * Number |
137 | * 978 |
138 | *
139 | *
140 | * z |
141 | * 时区 |
142 | * General time zone |
143 | * Pacific Standard Time; PST; GMT-08:00 |
144 | *
145 | *
146 | * Z |
147 | * 时区 |
148 | * RFC 822 time zone |
149 | * -0800 |
150 | *
151 | *
152 | *
153 | * HH:mm 15:44
154 | * h:mm a 3:44 下午
155 | * HH:mm z 15:44 CST
156 | * HH:mm Z 15:44 +0800
157 | * HH:mm zzzz 15:44 中国标准时间
158 | * HH:mm:ss 15:44:40
159 | * yyyy-MM-dd 2016-08-12
160 | * yyyy-MM-dd HH:mm 2016-08-12 15:44
161 | * yyyy-MM-dd HH:mm:ss 2016-08-12 15:44:40
162 | * yyyy-MM-dd HH:mm:ss zzzz 2016-08-12 15:44:40 中国标准时间
163 | * EEEE yyyy-MM-dd HH:mm:ss zzzz 星期五 2016-08-12 15:44:40 中国标准时间
164 | * yyyy-MM-dd HH:mm:ss.SSSZ 2016-08-12 15:44:40.461+0800
165 | * yyyy-MM-dd'T'HH:mm:ss.SSSZ 2016-08-12T15:44:40.461+0800
166 | * yyyy.MM.dd G 'at' HH:mm:ss z 2016.08.12 公元 at 15:44:40 CST
167 | * K:mm a 3:44 下午
168 | * EEE, MMM d, ''yy 星期五, 八月 12, '16
169 | * hh 'o''clock' a, zzzz 03 o'clock 下午, 中国标准时间
170 | * yyyyy.MMMMM.dd GGG hh:mm aaa 02016.八月.12 公元 03:44 下午
171 | * EEE, d MMM yyyy HH:mm:ss Z 星期五, 12 八月 2016 15:44:40 +0800
172 | * yyMMddHHmmssZ 160812154440+0800
173 | * yyyy-MM-dd'T'HH:mm:ss.SSSZ 2016-08-12T15:44:40.461+0800
174 | * EEEE 'DATE('yyyy-MM-dd')' 'TIME('HH:mm:ss')' zzzz 星期五 DATE(2016-08-12) TIME(15:44:40) 中国标准时间
175 | *
176 | */
177 | public static ThreadLocal DEFAULT_SDF = new ThreadLocal() {
178 | @Override
179 | protected SimpleDateFormat initialValue() {
180 | return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
181 | }
182 | };
183 | public static ThreadLocal CN_MM_DD_SDF = new ThreadLocal() {
184 | @Override
185 | protected SimpleDateFormat initialValue() {
186 | return new SimpleDateFormat("MM月dd日", Locale.getDefault());
187 | }
188 | };
189 | public static ThreadLocal CN_M_D_SDF = new ThreadLocal() {
190 | @Override
191 | protected SimpleDateFormat initialValue() {
192 | return new SimpleDateFormat("MM月dd日", Locale.getDefault());
193 | }
194 | };
195 | public static ThreadLocal CN_MM_DD_HH_MM_SDF = new ThreadLocal() {
196 | @Override
197 | protected SimpleDateFormat initialValue() {
198 | return new SimpleDateFormat("MM月dd日 HH:mm", Locale.getDefault());
199 | }
200 | };
201 | public static ThreadLocal EN_YYYY_MM_DD_SDF = new ThreadLocal() {
202 | @Override
203 | protected SimpleDateFormat initialValue() {
204 | return new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
205 | }
206 | };
207 | public static ThreadLocal EN_YYYY_MM_SDF = new ThreadLocal() {
208 | @Override
209 | protected SimpleDateFormat initialValue() {
210 | return new SimpleDateFormat("yyyy-MM", Locale.getDefault());
211 | }
212 | };
213 | public static ThreadLocal EN_YYYY_MM_DD_HH_MM_SDF = new ThreadLocal() {
214 | @Override
215 | protected SimpleDateFormat initialValue() {
216 | return new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault());
217 | }
218 | };
219 | public static ThreadLocal EN_YYYY_M_D_HH_MM_SDF = new ThreadLocal() {
220 | @Override
221 | protected SimpleDateFormat initialValue() {
222 | return new SimpleDateFormat("yyyy-M-d HH:mm", Locale.getDefault());
223 | }
224 | };
225 | public static ThreadLocal CN_YYYY_MM_DD_SDF = new ThreadLocal() {
226 | @Override
227 | protected SimpleDateFormat initialValue() {
228 | return new SimpleDateFormat("yyyy年MM月dd日", Locale.getDefault());
229 | }
230 | };
231 | public static ThreadLocal CN_YYYY_MM_DD_HH_MM_SDF = new ThreadLocal() {
232 | @Override
233 | protected SimpleDateFormat initialValue() {
234 | return new SimpleDateFormat("yyyy年MM月dd日 HH:mm", Locale.getDefault());
235 | }
236 | };
237 | public static ThreadLocal CN_YYYY_M_D_SDF = new ThreadLocal() {
238 | @Override
239 | protected SimpleDateFormat initialValue() {
240 | return new SimpleDateFormat("yyyy年M月d日", Locale.getDefault());
241 | }
242 | };
243 | public static ThreadLocal CN_YYYY_MM_DD_HH_MM_SS_SDF = new ThreadLocal() {
244 | @Override
245 | protected SimpleDateFormat initialValue() {
246 | return new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒", Locale.getDefault());
247 | }
248 | };
249 | public static ThreadLocal CN_YYYY_MM_DD_HH_MM_2_SDF = new ThreadLocal() {
250 | @Override
251 | protected SimpleDateFormat initialValue() {
252 | return new SimpleDateFormat("yyyy年MM月dd日HH时mm分", Locale.getDefault());
253 | }
254 | };
255 | public static ThreadLocal CN_YYYY_MM_DD_HH_MM_3_SDF = new ThreadLocal() {
256 | @Override
257 | protected SimpleDateFormat initialValue() {
258 | return new SimpleDateFormat("yyyy年M月d日H时m分", Locale.getDefault());
259 | }
260 | };
261 | public static ThreadLocal EN_M_D_SDF = new ThreadLocal() {
262 | @Override
263 | protected SimpleDateFormat initialValue() {
264 | return new SimpleDateFormat("M/d", Locale.getDefault());
265 | }
266 | };
267 | public static ThreadLocal EN_MM_DD_SDF = new ThreadLocal() {
268 | @Override
269 | protected SimpleDateFormat initialValue() {
270 | return new SimpleDateFormat("MM-dd", Locale.getDefault());
271 | }
272 | };
273 | public static ThreadLocal EN_YYYY_MM_DD_HH_SDF = new ThreadLocal() {
274 | @Override
275 | protected SimpleDateFormat initialValue() {
276 | return new SimpleDateFormat("yyyy-MM-dd HH", Locale.getDefault());
277 | }
278 | };
279 | public static ThreadLocal EN_YYYY_MM_DD_HH_SDFS = new ThreadLocal() {
280 | @Override
281 | protected SimpleDateFormat initialValue() {
282 | return new SimpleDateFormat("yyyy.MM.dd", Locale.getDefault());
283 | }
284 | };
285 | public static ThreadLocal EN_BIAS_YYYY_MM_DD_SDF = new ThreadLocal() {
286 | @Override
287 | protected SimpleDateFormat initialValue() {
288 | return new SimpleDateFormat("yyyy/MM/dd", Locale.getDefault());
289 | }
290 | };
291 | public static ThreadLocal EN_BIAS_YYYY_MM_DD_HH_MM_SDF = new ThreadLocal() {
292 | @Override
293 | protected SimpleDateFormat initialValue() {
294 | return new SimpleDateFormat("yyyy/MM/dd HH:mm", Locale.getDefault());
295 | }
296 | };
297 | public static ThreadLocal EN_H_MM_SDF = new ThreadLocal() {
298 | @Override
299 | protected SimpleDateFormat initialValue() {
300 | return new SimpleDateFormat("H:mm", Locale.getDefault());
301 | }
302 | };
303 | public static ThreadLocal EN_HH_mm = new ThreadLocal() {
304 | @Override
305 | protected SimpleDateFormat initialValue() {
306 | return new SimpleDateFormat("HH:mm", Locale.getDefault());
307 | }
308 | };
309 | public static ThreadLocal EN_YYYY_M_D_SDF = new ThreadLocal() {
310 | @Override
311 | protected SimpleDateFormat initialValue() {
312 | return new SimpleDateFormat("yyyy-M-d", Locale.getDefault());
313 | }
314 | };
315 |
316 | public static ThreadLocal EN_MM_DD_HH_MM_SDF =
317 | new ThreadLocal() {
318 | @Override
319 | protected SimpleDateFormat initialValue() {
320 | return new SimpleDateFormat("MM-dd HH:mm", Locale.getDefault());
321 | }
322 | };
323 |
324 | /**
325 | * 将时间戳转为时间字符串
326 | * 格式为yyyy-MM-dd HH:mm:ss
327 | *
328 | * @param milliseconds 毫秒时间戳
329 | * @return 时间字符串
330 | */
331 | public static String milliseconds2String(long milliseconds) {
332 | return milliseconds2String(milliseconds, DEFAULT_SDF.get());
333 | }
334 |
335 | /**
336 | * 将时间戳转为时间字符串
337 | * 格式为用户自定义
338 | *
339 | * @param milliseconds 毫秒时间戳
340 | * @param format 时间格式
341 | * @return 时间字符串
342 | */
343 | public static String milliseconds2String(long milliseconds, SimpleDateFormat format) {
344 | return format.format(new Date(milliseconds));
345 | }
346 |
347 | /**
348 | * 将时间字符串转为时间戳
349 | * 格式为yyyy-MM-dd HH:mm:ss
350 | *
351 | * @param time 时间字符串
352 | * @return 毫秒时间戳
353 | */
354 | public static long string2Milliseconds(String time) {
355 | return string2Milliseconds(time, DEFAULT_SDF.get());
356 | }
357 |
358 | /**
359 | * 将时间字符串转为时间戳
360 | * 格式为用户自定义
361 | *
362 | * @param time 时间字符串
363 | * @param format 时间格式
364 | * @return 毫秒时间戳
365 | */
366 | public static long string2Milliseconds(String time, SimpleDateFormat format) {
367 | try {
368 | return format.parse(time).getTime();
369 | } catch (ParseException e) {
370 | e.printStackTrace();
371 | }
372 | return -1;
373 | }
374 |
375 | /**
376 | * 将时间字符串转为Date类型
377 | * 格式为yyyy-MM-dd HH:mm:ss
378 | *
379 | * @param time 时间字符串
380 | * @return Date类型
381 | */
382 | public static Date string2Date(String time) {
383 | return string2Date(time, DEFAULT_SDF.get());
384 | }
385 |
386 |
387 | /**
388 | * 将时间字符串转为Date类型
389 | * 格式为用户自定义
390 | *
391 | * @param time 时间字符串
392 | * @param format 时间格式
393 | * @return Date类型
394 | */
395 | public static Date string2Date(String time, SimpleDateFormat format) {
396 | return new Date(string2Milliseconds(time, format));
397 | }
398 |
399 | /**
400 | * 将Date类型转为时间字符串
401 | * 格式为yyyy-MM-dd HH:mm:ss
402 | *
403 | * @param time Date类型时间
404 | * @return 时间字符串
405 | */
406 | public static String date2String(Date time) {
407 | return date2String(time, DEFAULT_SDF.get());
408 | }
409 |
410 | /**
411 | * 将Date类型转为时间字符串
412 | * 格式为用户自定义
413 | *
414 | * @param time Date类型时间
415 | * @param format 时间格式
416 | * @return 时间字符串
417 | */
418 | public static String date2String(Date time, SimpleDateFormat format) {
419 | return format.format(time);
420 | }
421 |
422 | /**
423 | * 将Date类型转为时间戳
424 | *
425 | * @param time Date类型时间
426 | * @return 毫秒时间戳
427 | */
428 | public static long date2Milliseconds(Date time) {
429 | return time.getTime();
430 | }
431 |
432 | /**
433 | * 将时间戳转为Date类型
434 | *
435 | * @param milliseconds 毫秒时间戳
436 | * @return Date类型时间
437 | */
438 | public static Date milliseconds2Date(long milliseconds) {
439 | return new Date(milliseconds);
440 | }
441 |
442 | /**
443 | * 毫秒时间戳单位转换(单位:unit)
444 | *
445 | * @param milliseconds 毫秒时间戳
446 | * @param unit
447 | * - {@link ConstUtils.TimeUnit#MSEC}: 毫秒
448 | * - {@link ConstUtils.TimeUnit#SEC }: 秒
449 | * - {@link ConstUtils.TimeUnit#MIN }: 分
450 | * - {@link ConstUtils.TimeUnit#HOUR}: 小时
451 | * - {@link ConstUtils.TimeUnit#DAY }: 天
452 | *
453 | * @return unit时间戳
454 | */
455 | private static long milliseconds2Unit(long milliseconds, ConstUtils.TimeUnit unit) {
456 | switch (unit) {
457 | case MSEC:
458 | return milliseconds / ConstUtils.MSEC;
459 | case SEC:
460 | return milliseconds / ConstUtils.SEC;
461 | case MIN:
462 | return milliseconds / ConstUtils.MIN;
463 | case HOUR:
464 | return milliseconds / ConstUtils.HOUR;
465 | case DAY:
466 | return milliseconds / ConstUtils.DAY;
467 |
468 | }
469 | return -1;
470 | }
471 |
472 | /**
473 | * 获取两个时间差(单位:unit)
474 | * time1和time2格式都为yyyy-MM-dd HH:mm:ss
475 | *
476 | * @param time0 时间字符串1
477 | * @param time1 时间字符串2
478 | * @param unit
479 | * - {@link ConstUtils.TimeUnit#MSEC}: 毫秒
480 | * - {@link ConstUtils.TimeUnit#SEC }: 秒
481 | * - {@link ConstUtils.TimeUnit#MIN }: 分
482 | * - {@link ConstUtils.TimeUnit#HOUR}: 小时
483 | * - {@link ConstUtils.TimeUnit#DAY }: 天
484 | *
485 | * @return unit时间戳
486 | */
487 | public static long getIntervalTime(String time0, String time1, ConstUtils.TimeUnit unit) {
488 | return getIntervalTime(time0, time1, unit, DEFAULT_SDF.get());
489 | }
490 |
491 | /**
492 | * 获取两个时间差(单位:unit)
493 | * time1和time2格式都为format
494 | *
495 | * @param time0 时间字符串1
496 | * @param time1 时间字符串2
497 | * @param unit
498 | * - {@link ConstUtils.TimeUnit#MSEC}: 毫秒
499 | * - {@link ConstUtils.TimeUnit#SEC }: 秒
500 | * - {@link ConstUtils.TimeUnit#MIN }: 分
501 | * - {@link ConstUtils.TimeUnit#HOUR}: 小时
502 | * - {@link ConstUtils.TimeUnit#DAY }: 天
503 | *
504 | * @param format 时间格式
505 | * @return unit时间戳
506 | */
507 | public static long getIntervalTime(String time0, String time1, ConstUtils.TimeUnit unit, SimpleDateFormat format) {
508 | return Math.abs(milliseconds2Unit(string2Milliseconds(time0, format)
509 | - string2Milliseconds(time1, format), unit));
510 | }
511 |
512 | /**
513 | * 获取两个时间差(单位:unit)
514 | * time1和time2都为Date类型
515 | *
516 | * @param time0 Date类型时间1
517 | * @param time1 Date类型时间2
518 | * @param unit
519 | * - {@link ConstUtils.TimeUnit#MSEC}: 毫秒
520 | * - {@link ConstUtils.TimeUnit#SEC }: 秒
521 | * - {@link ConstUtils.TimeUnit#MIN }: 分
522 | * - {@link ConstUtils.TimeUnit#HOUR}: 小时
523 | * - {@link ConstUtils.TimeUnit#DAY }: 天
524 | *
525 | * @return unit时间戳
526 | */
527 | public static long getIntervalTime(Date time0, Date time1, ConstUtils.TimeUnit unit) {
528 | return Math.abs(milliseconds2Unit(date2Milliseconds(time1)
529 | - date2Milliseconds(time0), unit));
530 | }
531 |
532 | /**
533 | * 获取两个毫秒值之间的时间差(天数)
534 | *
535 | * @param time1
536 | * @param time2 一般time2写较大的值
537 | * @return
538 | */
539 | public static int getIntervalTime(long time1, long time2) {
540 | return (int) ((time2 - time1) / (1000 * 3600 * 24));
541 | }
542 |
543 | /**
544 | * 获取当前时间
545 | *
546 | * @return 毫秒时间戳
547 | */
548 | public static long getCurTimeMills() {
549 | return System.currentTimeMillis();
550 | }
551 |
552 | /**
553 | * 获取当前时间
554 | * 格式为yyyy-MM-dd HH:mm:ss
555 | *
556 | * @return 时间字符串
557 | */
558 | public static String getCurTimeString() {
559 | return date2String(new Date());
560 | }
561 |
562 | /**
563 | * 获取当前时间
564 | * 格式为用户自定义
565 | *
566 | * @param format 时间格式
567 | * @return 时间字符串
568 | */
569 | public static String getCurTimeString(SimpleDateFormat format) {
570 | return date2String(new Date(), format);
571 | }
572 |
573 | /**
574 | * 获取当前时间
575 | * Date类型
576 | *
577 | * @return Date类型时间
578 | */
579 | public static Date getCurTimeDate() {
580 | return new Date();
581 | }
582 |
583 | /**
584 | * 获取与当前时间的差(单位:unit)
585 | * time格式为yyyy-MM-dd HH:mm:ss
586 | *
587 | * @param time 时间字符串
588 | * @param unit
589 | * - {@link ConstUtils.TimeUnit#MSEC}:毫秒
590 | * - {@link ConstUtils.TimeUnit#SEC }:秒
591 | * - {@link ConstUtils.TimeUnit#MIN }:分
592 | * - {@link ConstUtils.TimeUnit#HOUR}:小时
593 | * - {@link ConstUtils.TimeUnit#DAY }:天
594 | *
595 | * @return unit时间戳
596 | */
597 | public static long getIntervalByNow(String time, ConstUtils.TimeUnit unit) {
598 | return getIntervalByNow(time, unit, DEFAULT_SDF.get());
599 | }
600 |
601 | /**
602 | * 获取与当前时间的差(单位:unit)
603 | * time格式为format
604 | *
605 | * @param time 时间字符串
606 | * @param unit
607 | * - {@link ConstUtils.TimeUnit#MSEC}: 毫秒
608 | * - {@link ConstUtils.TimeUnit#SEC }: 秒
609 | * - {@link ConstUtils.TimeUnit#MIN }: 分
610 | * - {@link ConstUtils.TimeUnit#HOUR}: 小时
611 | * - {@link ConstUtils.TimeUnit#DAY }: 天
612 | *
613 | * @param format 时间格式
614 | * @return unit时间戳
615 | */
616 | public static long getIntervalByNow(String time, ConstUtils.TimeUnit unit, SimpleDateFormat format) {
617 | return getIntervalTime(getCurTimeString(), time, unit, format);
618 | }
619 |
620 | /**
621 | * 获取与当前时间的差(单位:unit)
622 | * time为Date类型
623 | *
624 | * @param time Date类型时间
625 | * @param unit
626 | * - {@link ConstUtils.TimeUnit#MSEC}: 毫秒
627 | * - {@link ConstUtils.TimeUnit#SEC }: 秒
628 | * - {@link ConstUtils.TimeUnit#MIN }: 分
629 | * - {@link ConstUtils.TimeUnit#HOUR}: 小时
630 | * - {@link ConstUtils.TimeUnit#DAY }: 天
631 | *
632 | * @return unit时间戳
633 | */
634 | public static long getIntervalByNow(Date time, ConstUtils.TimeUnit unit) {
635 | return getIntervalTime(getCurTimeDate(), time, unit);
636 | }
637 |
638 | /**
639 | * 判断闰年
640 | *
641 | * @param year 年份
642 | * @return {@code true}: 闰年
{@code false}: 平年
643 | */
644 | public static boolean isLeapYear(int year) {
645 | return year % 4 == 0 && year % 100 != 0 || year % 400 == 0;
646 | }
647 |
648 | /**
649 | * 获取当前日期是星期几
650 | *
651 | * @return 当前日期是星期几
652 | */
653 | public static String getWeekOfDate() {
654 | String[] weekDays = {"周日", "周一", "周二", "周三", "周四", "周五", "周六"};
655 | Calendar cal = Calendar.getInstance();
656 | cal.setTime(new Date());
657 |
658 | int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
659 | if (w < 0) {
660 | w = 0;
661 | }
662 |
663 | return weekDays[w];
664 | }
665 |
666 | /**
667 | * 获取当前日期是星期几
668 | *
669 | * @return 当前日期是星期几
670 | */
671 | public static String getWeek() {
672 | String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
673 | Calendar cal = Calendar.getInstance();
674 | cal.setTime(new Date());
675 |
676 | int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
677 | if (w < 0) {
678 | w = 0;
679 | }
680 |
681 | return weekDays[w];
682 | }
683 |
684 | /**
685 | * 获取当前日期的下一天是星期几
686 | *
687 | * @return 当前日期是星期几
688 | */
689 | public static String getWeekOfNextDate() {
690 | String[] weekDays = {"周日", "周一", "周二", "周三", "周四", "周五", "周六"};
691 | Calendar cal = Calendar.getInstance();
692 | cal.setTime(new Date());
693 |
694 | int w = cal.get(Calendar.DAY_OF_WEEK);
695 | if (w == 0) {
696 | w = 1;
697 | }
698 | if (w > 6) {
699 | w = 0;
700 | }
701 | return weekDays[w];
702 | }
703 |
704 | /**
705 | * 获取当前是年内的第几周
706 | *
707 | * @return
708 | */
709 | public static int getWeekOfYear() {
710 | int weekofyear = 0;
711 | try {
712 | Calendar c = Calendar.getInstance();
713 | c.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
714 | c.setFirstDayOfWeek(Calendar.MONDAY);/*设置周一为一周的第一天*/
715 | weekofyear = c.get(Calendar.WEEK_OF_YEAR);
716 | } catch (Exception e) {
717 | e.printStackTrace();
718 | }
719 | return weekofyear;
720 | }
721 |
722 | /**
723 | * 获取日历展示信息
724 | *
725 | * @return 返回日期+周几
726 | */
727 | public static String getCalendar() {
728 | return TimeUtils.getCurTimeString(TimeUtils.CN_MM_DD_SDF.get()) + " " + TimeUtils.getWeek();
729 | }
730 |
731 | /**
732 | * 获取桌面时钟的时间
733 | * 20180508 因该方法没被调用,且该方法需要 用到application的上下文,所以暂时注释掉
734 | */
735 | // public static String getDeskClockTime() {
736 | // ContentResolver cv = ActApplication.getAppContext().getContentResolver();
737 | // String strTimeFormat = android.provider.Settings.System.getString(cv,
738 | // android.provider.Settings.System.TIME_12_24);
739 | // int hour = "24".equals(strTimeFormat) ? Calendar.HOUR_OF_DAY : Calendar.HOUR;
740 | // Calendar c = Calendar.getInstance();
741 | //// c.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
742 | // c.setTimeZone(TimeZone.getDefault());
743 | // String mHuor = String.valueOf(c.get(hour));
744 | // if (hour == Calendar.HOUR && "0".equals(mHuor)) {
745 | // mHuor = "12";
746 | // }
747 | // String imnute = String.valueOf(c.get(Calendar.MINUTE));
748 | // if (imnute.length() < 2) {
749 | // imnute = "0" + imnute;
750 | // }
751 | // if (mHuor.length() < 2) {
752 | // mHuor = "0" + mHuor;
753 | // }
754 | // return mHuor + ":" + imnute;
755 | // }
756 |
757 | /**
758 | * 获取当前月份是几月
759 | */
760 | public static String getCurMonthStr() {
761 |
762 | Calendar c = Calendar.getInstance();
763 |
764 | int year = c.get(Calendar.YEAR);
765 | int month = c.get(Calendar.MONTH) + 1;
766 | String monthString = null;
767 |
768 | if (month < 10) {
769 |
770 | monthString = 0 + "" + month;
771 | } else {
772 |
773 | monthString = "" + month;
774 | }
775 |
776 | /**
777 | * 月份从0开始计算
778 | */
779 | return year + "-" + monthString;
780 | }
781 |
782 | /**
783 | * 获取当前月份
784 | *
785 | * @return
786 | */
787 | public static int getCurMonth() {
788 | int month = 0;
789 | try {
790 | Calendar c = Calendar.getInstance();
791 | c.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
792 | month = c.get(Calendar.MONTH) + 1;
793 | } catch (Exception e) {
794 | e.printStackTrace();
795 | }
796 | return month;
797 | }
798 |
799 | /**
800 | * 获取上个月月份
801 | *
802 | * @return
803 | */
804 | public static int getLastMonth() {
805 |
806 | int last = 1;
807 | int cur = getCurMonth();
808 | last = cur - 1;
809 | if (last == 0) {
810 | last = 12;
811 | }
812 | return last;
813 | }
814 |
815 | /**
816 | * 获取两个月份差值
817 | *
818 | * @param month1
819 | * @param month2
820 | * @return
821 | */
822 | public static int getDistanceOfTwoMonth(String month1, String month2) throws ParseException {
823 |
824 | SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
825 | Calendar bef = Calendar.getInstance();
826 | Calendar aft = Calendar.getInstance();
827 | bef.setTime(sdf.parse(month1));
828 | aft.setTime(sdf.parse(month2));
829 | int result = aft.get(Calendar.MONTH) - bef.get(Calendar.MONTH);
830 | int month = (aft.get(Calendar.YEAR) - bef.get(Calendar.YEAR)) * 12;
831 |
832 | return Math.abs(month + result);
833 | }
834 |
835 | /**
836 | * 判断旧日期和新日期【新旧根据获取先后而定】的先后关系,如果新日期大于旧日期则返回true
837 | */
838 | public static boolean compareDates(int oldYear, int oldMonth, int oldDay,
839 | int newYear, int newMonth, int newDay) {
840 | if (newYear != oldYear) {
841 | return !(newYear < oldYear);
842 | }
843 |
844 | if (newMonth != oldMonth) {
845 | return !(newMonth < oldMonth);
846 | }
847 |
848 | if (newDay != oldDay) {
849 | return !(newDay < oldDay);
850 | }
851 |
852 | return false;
853 | }
854 |
855 | /**
856 | * 获取当前时
857 | */
858 | public static int getHour() {
859 | final Calendar c = Calendar.getInstance();
860 | c.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
861 | return c.get(Calendar.HOUR_OF_DAY);
862 | }
863 |
864 | /**
865 | * 获取指定时间的小时
866 | */
867 | public static int getHour(long timeMills) {
868 | final Calendar c = Calendar.getInstance();
869 | c.setTimeInMillis(timeMills);
870 | c.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
871 | return c.get(Calendar.HOUR_OF_DAY);
872 | }
873 |
874 |
875 | /**
876 | * 获取当前月的天数
877 | *
878 | * @return
879 | */
880 | public static int getCurMonthLength() {
881 | Calendar a = Calendar.getInstance();
882 | a.set(Calendar.DATE, 1);
883 | a.roll(Calendar.DATE, -1);
884 | int maxDate = a.get(Calendar.DATE);
885 | return maxDate;
886 | }
887 |
888 | /**
889 | * 获取当前日期
890 | *
891 | * @return
892 | */
893 | public static String getCurDayOFMonth() {
894 | Calendar c = Calendar.getInstance();
895 | return String.valueOf(c.get(Calendar.DAY_OF_MONTH));
896 | }
897 |
898 | /**
899 | * 获取当前日期
900 | *
901 | * @return
902 | */
903 | public static int getCurDayOFMonthInt() {
904 | Calendar c = Calendar.getInstance();
905 | return c.get(Calendar.DAY_OF_MONTH);
906 | }
907 |
908 | /**
909 | * 获取当前年份
910 | *
911 | * @return
912 | */
913 | public static String getCurYear() {
914 | Calendar c = Calendar.getInstance();
915 | int year = c.get(Calendar.YEAR);
916 | return year + "";
917 | }
918 |
919 | /**
920 | * 获取当前是几号
921 | *
922 | * @return
923 | */
924 | public static int getDay() {
925 | Calendar c = Calendar.getInstance();
926 | int day = c.get(Calendar.DAY_OF_MONTH);
927 | return day;
928 | }
929 |
930 | /**
931 | * 获取年份
932 | *
933 | * @return
934 | */
935 | public static String getYear(long time) {
936 | Calendar c = Calendar.getInstance();
937 | c.setTimeInMillis(time);
938 | int year = c.get(Calendar.YEAR);
939 | return String.valueOf(year);
940 | }
941 |
942 | /**
943 | * 获取距离指定日期指定天数的日期
944 | *
945 | * @param current
946 | * @param diff
947 | * @return
948 | */
949 | public static String getDayByDiff(String current, int diff) {
950 | Calendar calendar = Calendar.getInstance();
951 | SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
952 | String result = null;
953 | try {
954 | calendar.setTime(format.parse(current));
955 | calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) + diff);
956 | result = format.format(calendar.getTime());
957 | } catch (ParseException e) {
958 | e.printStackTrace();
959 | }
960 | return result;
961 | }
962 |
963 | /**
964 | * 获取三天后的凌晨
965 | *
966 | * @return
967 | */
968 | public static long getThreeDaysLater() {
969 | return getTodayZero() + 3 * 24 * 60 * 60 * 1000L;
970 | }
971 |
972 | /**
973 | * 今天零点
974 | */
975 | public static long getTodayZero() {
976 | String timeStr = getCurTimeString(EN_YYYY_MM_DD_SDF.get());
977 | return string2Date(timeStr, EN_YYYY_MM_DD_SDF.get()).getTime();
978 | }
979 |
980 | /**
981 | * 明天零点
982 | *
983 | * @return
984 | */
985 | public static long getTomorrowZero() {
986 | return getTodayZero() + 24 * 60 * 60 * 1000L;
987 | }
988 |
989 |
990 | /**
991 | * 获取最近一个周末的日期
992 | *
993 | * @param style 返回结果样式 0 day/month 1 month.day
994 | * @return
995 | */
996 | private static String getLatestSunday(int style) {
997 | String result = "";
998 | try {
999 | Calendar c = Calendar.getInstance();
1000 | c.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
1001 | int mDayOfWeek = c.get(Calendar.DAY_OF_WEEK);
1002 | int diff = 0 - (mDayOfWeek - 1);
1003 | if (diff == 0) {
1004 | diff = -7;
1005 | }
1006 | c.setTime(new Date(System.currentTimeMillis()));
1007 | c.add(Calendar.DAY_OF_MONTH, diff);
1008 | String mDay = String.valueOf(c.get(Calendar.DAY_OF_MONTH));
1009 | int mMonth = c.get(Calendar.MONTH) + 1;// 获取mDay所在月份
1010 | if (style == 0) {
1011 | result = mDay + "/" + mMonth;
1012 | } else if (style == 1) {
1013 | result = mMonth + "." + mDay;
1014 | }
1015 | } catch (Exception e) {
1016 | e.printStackTrace();
1017 | }
1018 | return result;
1019 | }
1020 |
1021 | /**
1022 | * 获取最近一个周末的日期
1023 | *
1024 | * @param diffWeek -1:上一周的周一 -2:上两周的周一 。。。
1025 | * @return
1026 | */
1027 | public static String getLatestSundayDiff(int diffWeek) {
1028 | String result = "";
1029 | try {
1030 | Calendar c = Calendar.getInstance();
1031 | c.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
1032 | int mDayOfWeek = c.get(Calendar.DAY_OF_WEEK);
1033 | int diff = 0 - (mDayOfWeek - 1);
1034 | if (diff == 0) {
1035 | diff = -7;
1036 | }
1037 | diff = diff + (diffWeek * 7 + 1);
1038 | c.setTime(new Date(System.currentTimeMillis()));
1039 | c.add(Calendar.DAY_OF_MONTH, diff);
1040 | String mDay = String.valueOf(c.get(Calendar.DAY_OF_MONTH));
1041 | int mMonth = c.get(Calendar.MONTH) + 1;// 获取mDay所在月份
1042 | result = mMonth + "." + mDay;
1043 | } catch (Exception e) {
1044 | e.printStackTrace();
1045 | }
1046 | return result;
1047 | }
1048 |
1049 | /**
1050 | * 获取最近一个周末的日期
1051 | *
1052 | * @return [20170605, 20170610]
1053 | */
1054 | public static String[] getLatestWeekSpan(int diffWeek) {
1055 | String[] result = new String[2];
1056 | try {
1057 | Calendar c = Calendar.getInstance();
1058 | c.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
1059 | int mDayOfWeek = c.get(Calendar.DAY_OF_WEEK);
1060 | int diff = 0 - (mDayOfWeek - 1);
1061 | if (diff == 0) {
1062 | diff = -7;
1063 | }
1064 |
1065 | for (int i = 0; i < 2; i++) {
1066 | if (i == 0) {
1067 | diff = diff + (diffWeek * 7 + 1);
1068 | } else {
1069 | diff = diff + 6;
1070 | }
1071 | c.setTime(new Date(System.currentTimeMillis()));
1072 | c.add(Calendar.DAY_OF_MONTH, diff);
1073 | int day = c.get(Calendar.DAY_OF_MONTH);
1074 | String mDay = day + "";
1075 | if (day < 10) {
1076 | mDay = "0" + day;
1077 | }
1078 | // 获取mDay所在月份
1079 | int month = c.get(Calendar.MONTH) + 1;
1080 | String mMonth = month + "";
1081 | if (month < 10) {
1082 | mMonth = "0" + month;
1083 | }
1084 | int mYear = c.get(Calendar.YEAR);
1085 | result[i] = mYear + "" + mMonth + "" + mDay;
1086 | }
1087 | } catch (Exception e) {
1088 | e.printStackTrace();
1089 | }
1090 | return result;
1091 | }
1092 |
1093 | /**
1094 | * 获取最近一周的日期---点分式-周报页面
1095 | *
1096 | * @return
1097 | */
1098 | public static String getLatestSundayDot() {
1099 |
1100 | String result = "";
1101 | try {
1102 | Calendar c = Calendar.getInstance();
1103 | c.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
1104 | int mDayOfWeek = c.get(Calendar.DAY_OF_WEEK);
1105 | // 0 1 2 3 4 5 6
1106 | int diff = 0 - (mDayOfWeek - 1);
1107 | if (diff == 0) {
1108 | diff = -7;
1109 | }
1110 | c.setTime(new Date(System.currentTimeMillis()));
1111 | c.add(Calendar.DAY_OF_MONTH, diff);
1112 | String mDay = String.valueOf(c.get(Calendar.DAY_OF_MONTH));
1113 | // 获取mDay所在月份
1114 | String mMonth = c.get(Calendar.MONTH) + 1 + "";
1115 | if (mMonth.length() == 1) {
1116 | mMonth = 0 + "" + mMonth;
1117 | }
1118 | if (mDay.length() == 1) {
1119 | mDay = 0 + mDay;
1120 | }
1121 | result = mMonth + "." + mDay;
1122 | } catch (Exception e) {
1123 | e.printStackTrace();
1124 | }
1125 | return result;
1126 | }
1127 |
1128 | /**
1129 | * 获取最近一月的日期---空格分式-月报页面
1130 | *
1131 | * @return
1132 | */
1133 | public static String getLastMonthDot() {
1134 | String result = "";
1135 | try {
1136 | Calendar c = Calendar.getInstance();
1137 | c.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
1138 | c.setTime(new Date(System.currentTimeMillis()));
1139 | c.add(Calendar.MONTH, -1);
1140 | // 获取mDay所在月份
1141 | String mMonth = c.get(Calendar.MONTH) + 1 + "";
1142 | String mYear = c.get(Calendar.YEAR) + "";
1143 | if (mMonth.length() == 1) {
1144 | mMonth = 0 + "" + mMonth;
1145 | }
1146 | result = mYear + "年" + mMonth + "月";
1147 | } catch (Exception e) {
1148 | e.printStackTrace();
1149 | }
1150 | return result;
1151 | }
1152 |
1153 | /**
1154 | * 获取上一月的日期---年、月[0-11]
1155 | *
1156 | * @param interval -1:之前1个月 -2之前两个月 -3:之前三个月。。。以此类推
1157 | * @return
1158 | */
1159 | public static String[] getLastMonthYear(int interval) {
1160 | String[] result = new String[]{"2017", "1"};
1161 | try {
1162 | Calendar c = Calendar.getInstance();
1163 | c.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
1164 | c.setTime(new Date(System.currentTimeMillis()));
1165 | c.add(Calendar.MONTH, interval);
1166 | String mMonth = c.get(Calendar.MONTH) + "";
1167 | String mYear = c.get(Calendar.YEAR) + "";
1168 | result[0] = mYear;
1169 | result[1] = mMonth;
1170 | } catch (Exception e) {
1171 | e.printStackTrace();
1172 | }
1173 | return result;
1174 | }
1175 |
1176 | public static String[] getLastMonthRecord(int interval) {
1177 | String[] result = new String[]{"2017", "1"};
1178 | try {
1179 | Calendar c = Calendar.getInstance();
1180 | c.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
1181 | c.setTime(new Date(System.currentTimeMillis()));
1182 | c.add(Calendar.MONTH, interval);
1183 | String mMonth = (c.get(Calendar.MONTH) + 1) + "";
1184 | String mYear = c.get(Calendar.YEAR) + "";
1185 | result[0] = mYear;
1186 | result[1] = mMonth;
1187 | } catch (Exception e) {
1188 | e.printStackTrace();
1189 | }
1190 | return result;
1191 | }
1192 |
1193 | /**
1194 | * 根据日期获取周几
1195 | *
1196 | * @param date:2017-06-04
1197 | */
1198 | public static String getDayOfWeekByDate(String date) {
1199 | String[] dayOfWeek;
1200 | Calendar calendar;
1201 | String result;
1202 | try {
1203 | dayOfWeek = new String[]{"default", "周日", "周一", "周二", "周三", "周四", "周五", "周六"};
1204 | SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
1205 | Date date1 = sdf.parse(date);
1206 | calendar = Calendar.getInstance();
1207 | calendar.setTime(date1);
1208 | result = dayOfWeek[calendar.get(Calendar.DAY_OF_WEEK)];
1209 | } catch (ParseException e) {
1210 | result = date;
1211 | e.printStackTrace();
1212 | }
1213 | return result;
1214 | }
1215 |
1216 | /**
1217 | * 根据日期获取周几
1218 | *
1219 | * @param :geshi:2017-06-04
1220 | * @param date 预报中第一天的日期
1221 | * @param index 第几天
1222 | */
1223 | public static String getDayOfWeekByDate(long date, int index) {
1224 | String[] dayOfWeek;
1225 | Calendar calendar;
1226 | String result;
1227 | try {
1228 | dayOfWeek = new String[]{"default", "周日", "周一", "周二", "周三", "周四", "周五", "周六"};
1229 | Date date1 = new Date(date);
1230 | calendar = Calendar.getInstance();
1231 | calendar.setTime(date1);
1232 | calendar.add(calendar.DATE, index);
1233 | result = dayOfWeek[calendar.get(Calendar.DAY_OF_WEEK)];
1234 | } catch (Exception e) {
1235 | SimpleDateFormat sdf = new SimpleDateFormat("MM/dd");
1236 | calendar = Calendar.getInstance();
1237 | calendar.setTime(new Date(date));
1238 | calendar.add(calendar.DATE, index);
1239 | result = sdf.format(calendar.getTime());
1240 | e.printStackTrace();
1241 | }
1242 | return result;
1243 | }
1244 |
1245 | /**
1246 | * 获取上周周几的日期,默认一周从周一开始
1247 | *
1248 | * @param dayOfWeek
1249 | * @param weekOffset
1250 | * @return
1251 | */
1252 | public static Date getDayOfWeek(int dayOfWeek, int weekOffset) {
1253 | return getDayOfWeek(Calendar.MONDAY, dayOfWeek, weekOffset);
1254 | }
1255 |
1256 | /**
1257 | * 获取上(下)周周几的日期
1258 | *
1259 | * @param firstDayOfWeek {@link Calendar}
1260 | * 值范围 SUNDAY,
1261 | * MONDAY, TUESDAY, WEDNESDAY,
1262 | * THURSDAY, FRIDAY, and SATURDAY
1263 | * @param dayOfWeek {@link Calendar}
1264 | * @param weekOffset 周偏移,上周为-1,本周为0,下周为1,以此类推
1265 | * @return
1266 | */
1267 | public static Date getDayOfWeek(int firstDayOfWeek, int dayOfWeek, int weekOffset) {
1268 | if (dayOfWeek > Calendar.SATURDAY || dayOfWeek < Calendar.SUNDAY) {
1269 | return null;
1270 | }
1271 | if (firstDayOfWeek > Calendar.SATURDAY || firstDayOfWeek < Calendar.SUNDAY) {
1272 | return null;
1273 | }
1274 | Calendar date = Calendar.getInstance(Locale.CHINA);
1275 | date.setFirstDayOfWeek(firstDayOfWeek);
1276 | //周数减一,即上周
1277 | date.add(Calendar.WEEK_OF_MONTH, weekOffset);
1278 | //日子设为周几
1279 | date.set(Calendar.DAY_OF_WEEK, dayOfWeek);
1280 | //时分秒全部置0
1281 | date.set(Calendar.HOUR_OF_DAY, 0);
1282 | date.set(Calendar.MINUTE, 0);
1283 | date.set(Calendar.SECOND, 0);
1284 | date.set(Calendar.MILLISECOND, 0);
1285 | return date.getTime();
1286 | }
1287 |
1288 | /**
1289 | * 将毫秒值转化为友好的时间表达格式
1290 | * 今天 14:52
1291 | * 明天 14:52
1292 | * 昨天 14:52
1293 | * 年一样,日期非今天昨天明天,返回08-12 14:52
1294 | * 年不一样,返回2018-08-12 14:52
1295 | */
1296 | public static String milliseconds2FriendlyString(long milliseconds) {
1297 | return date2FriendlyString(new Date(milliseconds));
1298 | }
1299 |
1300 | /**
1301 | * 将Date类型转化为友好的时间表达格式
1302 | * 今天 14:52
1303 | * 明天 14:52
1304 | * 昨天 14:52
1305 | * 年一样,日期非今天昨天明天,返回08-12 14:52
1306 | * 年不一样,返回2018-08-12 14:52
1307 | */
1308 | public static String date2FriendlyString(Date date) {
1309 | Calendar targetCalendar = Calendar.getInstance();
1310 | targetCalendar.setTime(date);
1311 | Calendar currentCalendar = Calendar.getInstance();
1312 | if (currentCalendar.get(Calendar.YEAR) != targetCalendar.get(Calendar.YEAR)) {
1313 | return EN_YYYY_MM_DD_HH_MM_SDF.get().format(date);
1314 | } else {
1315 | int diffDay = currentCalendar.get(Calendar.DAY_OF_YEAR) - targetCalendar.get(
1316 | Calendar.DAY_OF_YEAR);
1317 | if (diffDay == 1) {
1318 | return "昨天 " + EN_HH_mm.get().format(date);
1319 | } else if (diffDay == 0) {
1320 | return "今天 " + EN_HH_mm.get().format(date);
1321 | } else if (diffDay == -1) {
1322 | return "明天 " + EN_HH_mm.get().format(date);
1323 | } else {
1324 | return EN_MM_DD_HH_MM_SDF.get().format(date);
1325 | }
1326 | }
1327 | }
1328 |
1329 | /**
1330 | * 将毫秒值转化为友好的时间表达格式
1331 | * 今天 14:52
1332 | * 明天 14:52
1333 | * 昨天 14:52
1334 | * 年一样,日期非今天昨天明天,返回08-12 14:52
1335 | * 年不一样,返回2018-08-12 14:52
1336 | */
1337 | public static String milliseconds2FriendlyStringCN(long milliseconds) {
1338 | return date2FriendlyStringCN(new Date(milliseconds));
1339 | }
1340 |
1341 | /**
1342 | * 将Date类型转化为友好的时间表达格式
1343 | * 今天 14:52
1344 | * 明天 14:52
1345 | * 昨天 14:52
1346 | * 年一样,日期非今天昨天明天,返回08-12 14:52
1347 | * 年不一样,返回2018-08-12 14:52
1348 | */
1349 | public static String date2FriendlyStringCN(Date date) {
1350 | Calendar targetCalendar = Calendar.getInstance();
1351 | targetCalendar.setTime(date);
1352 | Calendar currentCalendar = Calendar.getInstance();
1353 | if (currentCalendar.get(Calendar.YEAR) != targetCalendar.get(Calendar.YEAR)) {
1354 | return EN_YYYY_MM_DD_HH_MM_SDF.get().format(date);
1355 | } else {
1356 | int diffDay = currentCalendar.get(Calendar.DAY_OF_YEAR) -
1357 | targetCalendar.get(Calendar.DAY_OF_YEAR);
1358 | if (diffDay == 1) {
1359 | return "昨天 " + EN_HH_mm.get().format(date);
1360 | } else if (diffDay == 0) {
1361 | return "今天 " + EN_HH_mm.get().format(date);
1362 | } else if (diffDay == -1) {
1363 | return "明天 " + EN_HH_mm.get().format(date);
1364 | } else {
1365 | return CN_MM_DD_HH_MM_SDF.get().format(date);
1366 | }
1367 | }
1368 | }
1369 |
1370 | }
--------------------------------------------------------------------------------