/
QuickDateUtils.kt
79 lines (63 loc) · 2.28 KB
/
QuickDateUtils.kt
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
@file:Suppress("unused", "MemberVisibilityCanBePrivate")
package com.rzahr.quicktools.utils
import android.annotation.SuppressLint
import android.os.Build
import androidx.annotation.RequiresApi
import java.text.SimpleDateFormat
import java.time.LocalDate
import java.time.format.DateTimeFormatter
import java.util.*
/**
* @author Rashad Zahr
*
* object used as a helper for date-related functions
*/
object QuickDateUtils {
const val DASHED_FORMAT = "yyyy-MM-dd HH:mm:ss"
const val SLASHED_FORMAT = "dd/MM/yyyy hh:mm:ss a"
fun convertToDate(dateString: String, format: String = DASHED_FORMAT): Date? {
return SimpleDateFormat(format, Locale.ENGLISH).parse(dateString)
}
@RequiresApi(Build.VERSION_CODES.O)
fun convertToLocalDate(dateString: String, format: String = DASHED_FORMAT): LocalDate {
val formatter = DateTimeFormatter.ofPattern(format, Locale.ENGLISH)
return LocalDate.parse(dateString, formatter)
}
/**
* returns a string date
* @param date the date
* @param format the format
* @return a date string
*/
fun getDateString(date: Date, format: String = DASHED_FORMAT): String {
val calendar = Calendar.getInstance()
calendar.time = date
return SimpleDateFormat(format, Locale.ENGLISH).format(calendar.time)
}
/**
* get the current date in a string format
* @param english the language if english
* @param format the format
* @return a date string
*/
@SuppressLint("SimpleDateFormat")
fun getCurrentDate(english: Boolean = true, format: String = DASHED_FORMAT): String {
val now = Date()
return if (english)
SimpleDateFormat(format, Locale.ENGLISH).format(now)
else
SimpleDateFormat(format).format(now)
}
/**
* changes the time to string
* @param dateLong the date
* @param format the format
* @param timeZone the timezone
* @return date string
*/
fun changeTimeToString(dateLong: Long, format: String = SLASHED_FORMAT, timeZone: TimeZone? = null): String {
val simpleDateFormat = SimpleDateFormat(format, Locale.ENGLISH)
if (timeZone != null) simpleDateFormat.timeZone = timeZone
return simpleDateFormat.format(Date(dateLong).time)
}
}