summaryrefslogtreecommitdiffstats
path: root/dozentenmodul/src/main/java/org/openslx/dozmod/util/FormatHelper.java
blob: 5b36a18c082fced79de79e76006106c8905cf9e7 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package org.openslx.dozmod.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;

public class FormatHelper {

	private static final SimpleDateFormat in = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	private static final SimpleDateFormat out = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss");

	/**
	 * Convert mysql date/time format to human readable (German) format.
	 * If the given date is not parsable, "<invalid>" will be returned.
	 * 
	 * @param dateTime yyyy-MM-dd HH:mm:ss
	 * @return dd.MM.yy HH:mm
	 */
	public static String mysqlDateToGerman(String dateTime) {
		try {
			return out.format(in.parse(dateTime));
		} catch (ParseException e) {
			return "<invalid>";
		}
	}

	public static String byteToGigabyte(long bytes, boolean si) {
		int unit = si ? 1000 : 1024;
		if (bytes < unit)
			return bytes + " B";
		int exp = (int) (Math.log(bytes) / Math.log(unit));
		String pre = (si ? "kMGTPE" : "KMGTPE").charAt(exp - 1) + (si ? "" : "i");
		return String.format("%.1f %sB", bytes / Math.pow(unit, exp), pre);
	}

	/**
	 * Parse the given String as a base10 integer.
	 * If the string does not represent a valid integer, return the given
	 * default value.
	 * 
	 * @param value string representation to parse to an int
	 * @param defaultValue fallback value if given string can't be parsed
	 * @return
	 */
	public static int parseInt(String value, int defaultValue) {
		try {
			return Integer.parseInt(value);
		} catch (Exception e) {
			return defaultValue;
		}
	}

}