Date Operations in Swift and Android

Author - Nancy & Satish

Dealing with Date is the most common stuff for developers. More or less they need to deal with Date while developing. The frequently and generally used operation of Date includes getting a string from Date object to arithmetic operations on Date.

The other operations related to Date includes getting particular component (day, month, year) from Date object, difference between Dates, comparison of two dates, addition or subtraction of particular component(day, month, year, hours, minutes, seconds) to Date object, conversion of Date between different TimeZone. Also we can check if the Date is today’s Date, getting weekday from Date, day of Date is weekday or weekend.

The LIDateUtility & LIDateUtil class present for Swift & Android respectively contains such operations related to Date. By using this class, you can complete your requirements by just calling the method. And in case, of frequent use of Date in your code, the amount of code will also get reduced with the help of this class.

There are many Date Operations we can do. Here are some of the most useful Date Operations below :-

1)  Get Current Year

This function returns the current Year of today’s Date. the following example returns the current Year from the current Date. Here is an example of Swift and Android. getCurrentYear() method is defined in the LIDateUtility & LIDateUtil class for Swift & Android.

*Swift

let currentYear = LIDateUtility.getCurrentYear()
print("Current year: \(currentYear)")

public static func getCurrentYear() -> Int{
    return Calendar.current.component(.year, from: Date())
}
*Android

int currentYear = LIDateUtil.getCurrentYear();
Log.d(TAG, "Current Year = "+currentYear);

public static int getCurrentYear() {
    return Calendar.getInstance().get(Calendar.YEAR);
}

2)  Get Current Month

This function returns the current Month from today’s Date. the following example returns the current Month from the current Date. Here is an example of Swift and Android. getCurrentMonth() Method is defined in the LIDateUtility & LIDateUtil class for Swift & Android.

*Swift

let currentMonth = LIDateUtility.getCurrentMonth()
print("Current Month: \(currentMonth)")

public static func getCurrentMonth() -> Int{
    return Calendar.current.component(.month, from: Date())
}
*Android

int currentMonth = LIDateUtil.getCurrentMonth();
Log.d(TAG, "Current Month = "+currentMonth);

public static int getCurrentMonth() {
    return Calendar.getInstance().get(Calendar.MONTH);
}

3)  Get Current Day

This function returns current Day from today’s Date. the following example returns the current Day from the current Date. Here is an example of Swift and Android. getCurrentDay() method is defined in the LIDateUtility & LIDateUtil class for Swift & Android.

*Swift

let currentDay = LIDateUtility.getCurrentDay()
print("Current Date: \(currentDay)")

public static func getCurrentDay() -> Int{
    return Calendar.current.component(.day, from: Date())
}
*Android

int currentDay= LIDateUtil.getCurrentDay();
Log.d(TAG, "Current Day = "+currentDay);

public static int getCurrentDay() {
    return Calendar.getInstance().get(Calendar.DATE);
}

4) Get Year from Date

This function returns the Year from specific Date. The following example returns the Year from specific Date. Here is an example of Swift and Android. getYearFromDate(date: Date) method is defined in the LIDateUtility & LIDateUtil class for Swift & Android.

*Swift

var component = DateComponents()
component.day = 12
component.month = 3
component.year = 2020
let date = Calendar.current.date(from: component)
let year = LIDateUtility.getYearFromDate(date: date!)
print("Year of date: \(year)")

public static func getYearFromDate(date: Date) -> Int{
    let year = Calendar.current.dateComponents([.year], from: date)
    return (year.year!)
}
*Android

Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR,2020);
calendar.set(Calendar.MONTH,9);
calendar.set(Calendar.DATE,21);

int year = LIDateUtil.getYearFromDate(calendar.getTime());
Log.d(TAG, "Year of date = "+year);

public static int getYearFromDate(Date d) {
    Calendar calendar = getCalender(d);
    return calendar.get(Calendar.YEAR);
}

5) Get Month from Date

This function returns the Month from specific Date. The following example return the Month from specific Date. Here is an example of Swift and Android. getMonthFromDate(date: Date) method is define in the LIDateUtility & LIDateUtil class for Swift & Android.

*Swift

var component = DateComponents()
component.day = 12
component.month = 3
component.year = 2020
let date = Calendar.current.date(from: component)
let month = LIDateUtility.getMonthFromDate(date: date!)
print("Month of date: \(month)")

public static func getMonthFromDate(date: Date) -> Int{
    let month = Calendar.current.dateComponents([.month], from: date)
    return (month.month!)
}
*Android

Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR,2020);
calendar.set(Calendar.MONTH,9);
calendar.set(Calendar.DATE,21);

int month = LIDateUtil.getMonthFromDate(calendar.getTime());
Log.d(TAG, "Month of date = "+month);

public static int getMonthFromDate(Date d) {
    Calendar calendar = getCalender(d);
    return calendar.get(Calendar.MONTH);
}

6) Get Day from Date

This function returns the Day from specific Date. The following example returns the Day from specific Date. Here is an example of Swift and Android. getDayFromDate(date: Date) method is defined in the LIDateUtility & LIDateUtil class for Swift & Android.

*Swift

var component = DateComponents()
component.day = 12
component.month = 3
component.year = 2020
let date = Calendar.current.date(from: component)
let day = LIDateUtility.getDayFromDate(date: dDate!)
print("Day of date: \(day)")

public static func getDayFromDate(date: Date) -> Int{
    let date = Calendar.current.dateComponents([.day], from: date)
    return (date.day!)
}
*Android

Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR,2020);
calendar.set(Calendar.MONTH,9);
calendar.set(Calendar.DATE,21);

int day = LIDateUtil.getDayFromDate(calendar.getTime());
Log.d(TAG, "Day of date = "+day);

public static int getDayFromDate(Date d) {
    Calendar calendar = getCalender(d);
    return calendar.get(Calendar.DATE);
}

7) Get Time from Date

This function returns the Time from specific Date. The following example returns the Time from specific Date. Here is an example of Swift and Android. getTimeFromDate(date: Date) method is defined in the LIDateUtility & LIDateUtil class for Swift & Android.

*Swift

let time = LIDateUtility.getTimeFromDate(date: Date())
print(“Time: \(time)”)

public static func getTimeFromDate(date: Date) -> String{
    let calendar = Calendar.current
    let time = calendar.dateComponents([.hour, .minute, .second], from: from)
    return "\(time.hour!):\(time.minute!):\(time.second!)"
 }
*Android

String time = LIDateUtil.getTimeFromDate(new Date());
Log.d(TAG, "Time of date = "+time);

public static String getTimeFromDate(Date d) {
    return getStringFromDate(d,TIME_24);
}

8) Get Name of Week Day from Date

This functions returns the Weekday from specific Date. Here is an example of Swift and Android. getWeekDayFromDate(date: Date) method is defined in the LIDateUtility & LIDateUtil class for Swift & Android.

*Swift

let dayOfWeek = LIDateUtility.getWeekDayFromDate(date: Date())
print("Day of week of date: \(dayOfWeek)")

public static func getWeekDayFromDate(date: Date) -> String {
    let formatter = DateFormatter()
    let day = formatter.weekdaySymbols[Calendar.current.component(.weekday, from: date)-1]
    return day
}
*Android

String weekday = LIDateUtil.getWeekDayFromDate(new Date());
Log.d(TAG, "Day of week of date = "+weekday);

public static String getWeekDayFromDate(Date d) {
    return getStringFromDate(d,"EEEE");
}

9) Date from String

This function returns the Date from String. Here is an example of Swift and Android. getDateFromString(stringDate: “01-03-2011 10:12:45”, format: “dd-MM-yyyy HH:mm:ss”) method is defined in the LIDateUtility & LIDateUtil class for Swift & Android. We have put “if condition” because if you pass the wrong format of the Date then String to Date conversation will return nil.

*Swift

if let datefromstring = LIDateUtility.getDateFromString(stringDate: "01-03-2011 10:12:45", format: "dd-MM-yyyy HH:mm:ss"){
    print("Date from string: \(datefromstring)")
}
public static func getDateFromString(stringDate: String, format: String) -> Date? {
    let formatter = DateFormatter()
    formatter.dateFormat = format
    return formatter.date(from: stringDate)
}
*Android

Date date = LIDateUtil.getDateFromString("11-08-2012 10:12:15","dd-MM-yyyy HH:mm:ss");
Log.d(TAG, "Date from string = "+date);


public static Date getDateFromString(String stringDate, String format) {
    SimpleDateFormat input = new SimpleDateFormat(format);
    Date date = null;
    Calendar calendar = null;
    try {
        date = input.parse(stringDate);
        calendar = Calendar.getInstance();
        calendar.setTime(date);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return calendar.getTime();
}

10) String from Date

This function returns a String from Date. Here is an example of Swift and Android. getStringFromDate(date: date, format: “dd-MM-yyyy”) method is defined in the LIDateUtility & LIDateUtil class for Swift & Android.

*Swift

let stringFromDate = LIDateUtility.getStringFromDate(date: date, format: "dd-MM-yyyy")
print("String from date: \(stringFromDate)")

public static func getStringFromDate(date: Date, format: String) -> String{
    let formatter = DateFormatter()
    formatter.dateFormat = format
    let strDate = formatter.string(from: date)
    return strDate
}
*Android

Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR,2020);
calendar.set(Calendar.MONTH,9);
calendar.set(Calendar.DATE,21);
String date1 = LIDateUtil.getStringFromDate(calendar.getTime(),"dd-MM-yyyy HH:mm:ss");
Log.d(TAG, "String form date = "+date1);

public static String getStringFromDate(Date date, String format) {
    return DateFormat.format(format, date).toString();
}

11) Get Timestamp from Date

This function returns the Timestamp from the Date. Here is an example of Swift and Android. getTimestampFromDate(date: Date()) method is defined in the LIDateUtility & LIDateUtil class for Swift & Android.

*Swift

let timeStamp = LIDateUtility.getTimestampFromDate(date: Date()) 
print("Timestamp from date: \(timeStamp)")

public static func getTimestampFromDate(date: Date) -> Int64 {
    let miliSeconds = date.timeIntervalSince1970
    return Int64(Int(miliSeconds*1000))
}
*Android

long timeStamp = LIDateUtil.getTimeStampFromDate(new Date());
Log.d(TAG, "Timestamp from date = "+timeStamp);

public static long getTimeStampFromDate(Date date){
    return date.getTime();
}

12) Get Date from Timestamp

This function will return the Date from the Timestamp. Here is an example of Swift and Android. getDateFromTimestamp(timeStamp: 1552292651767) method is defined in the  LIDateUtility  LIDateUtil class for Swift & Android.

*Swift

let dateFromTimestamp = LIDateUtility.getDateFromTimestamp(timeStamp: 1552292651767)
print("Date from Timestamp: \(dateFromTimestamp)")

public static func getDateFromTimestamp(timeStamp: Int64) -> Date {
    return Date(timeIntervalSince1970: TimeInterval(timeStamp)/1000)
}
*Android

Date date3 = LIDateUtil.getDateFromTimeStamp(1553850285056l);
Log.d(TAG, "Date from Timestamp = "+date3);


public static Date getDateFromTimeStamp(long milliSeconds) {
    // Create a calendar object that will convert the date and time value in milliseconds to date.
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(milliSeconds);
    return calendar.getTime();
}

13) Get Age

This function returns the Age in Year. Here is an example of Swift and Android. getAge(birthDate: date!) method is defined in the LIDateUtility & LIDateUtil class for Swift & Android.

*Swift

var component = DateComponents()
component.day = 11
component.month = 4
component.year = 2009
let date = Calendar.current.date(from: component)
if let age = LIDateUtility.getAge(birthDate: date!){
    print("\nAge: \(age)")
}else{
    print("\nAge: Invalid birth date")
}

public static func getAge(birthDate: Date) -> Int? {
    switch birthDate.compare(Date()) {
        case .orderedSame: return 0
        case .orderedAscending:
        let age = Calendar.current.dateComponents([.year], from: birthDate, to: Date())
        return age.year
        case .orderedDescending: return nil
        default:
            return 0
    }
}
*Android

Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR,1990);
calendar.set(Calendar.MONTH,9);
calendar.set(Calendar.DATE,21);
int age = LIDateUtil.getAge(calendar.getTime());
Log.d(TAG, "Age = "+age);


public static int getAge(Date d) {
    Calendar dob = getCalender(d);
    Calendar today = Calendar.getInstance();
    int age = today.get(Calendar.YEAR) - dob.get(Calendar.YEAR);
    if (today.get(Calendar.DAY_OF_YEAR) < dob.get(Calendar.DAY_OF_YEAR)) {
        age--;
    }
    return age;
}

14) Compare Two Dates

This function we can use to compare two Date objects. Here is an example of Swift and Android. It returns String containing message if two dates are same/ first date is earlier then the second date/ first date is later than the second date.

*Swift

var component = DateComponents()
component.day = 12
component.month = 3
component.year = 2020
let date = Calendar.current.date(from: component)

let comparisonString = LIDateUtility.compareDates(date1: Date(), date2: date)) 
print("Comparison of dates: \(comparisonString)")

public static func compareDates(date1: Date, date2: Date) -> String {
    switch date1.compare(date2){
        case .orderedSame: return "The two dates are same"
        case .orderedAscending: return "Date1 is earlier than date2"
        case .orderedDescending: return "Date1 is later than date2"
        default:
            return "Sorry! Can't compare"
    }
}

*Android

Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR,1990);
calendar.set(Calendar.MONTH,9);
calendar.set(Calendar.DATE,21);

switch (LIDateUtil.compareDates(calendar.getTime(),new Date())){
    case LIDateUtil.GREATER:
        Log.d(TAG, "Date is Greater: ");
        break;
    case LIDateUtil.LESSER:
        Log.d(TAG, "Date is lesser: ");
        break;
    case LIDateUtil.EQUALS:
        Log.d(TAG, "Date is equals: ");
        break;
}

public static int compareDates(Date date1, Date date2) {
    if (date1 != null && date2 != null) {
    int retVal = date1.compareTo(date2);
    if (retVal > 0)
        return GREATER; // date1 is greatet than date2
    else if (retVal == 0) // both dates r equal
        return EQUALS;
    }
    return LESSER; // date1 is less than date2
}

15) Get Difference between Two Dates in Days

This function returns the number of Days difference from two Dates. The following example returns the number of Days difference from two Dates. Here is an example of Swift and Android. getDifferenceBetweenTwoDatesInDays(date1: Date, date2: Date) method is defined in the  LIDateUtility LIDateUtil class for Swift & Android.

*Swift

var component = DateComponents()
component.day = 12
component.month = 3
component.year = 2020
let date = Calendar.current.date(from: component)

let differenceInDays = LIDateUtility.getDifferenceBetweenTwoDatesInDays(date1: Date(), date2: date!) 
print("Difference of days: \(differenceInDays)")

public static func getDifferenceBetweenTwoDatesInDays(date1: Date, date2: Date) -> Int {
    let days = Calendar.current.dateComponents([.day], from: date1, to: date2)
    return days.day ?? 0
}
*Android

Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR,1990);
calendar.set(Calendar.MONTH,9);
calendar.set(Calendar.DATE,21);
int diffDays = LIDateUtil.getDifferenceBetweenTwoDatesInDays(calendar.getTime(),new Date());
Log.d(TAG, "Diffrence of Days = "+diffDays);

public static int getDifferenceBetweenTwoDatesInDays(Date fromDate, Date toDate) {
    return Math.abs((int) ((toDate.getTime() - fromDate.getTime()) / (1000 * 60 * 60 * 24)));
}

16) Get Difference between Two Dates in Months

This function returns the number of Months difference from two Dates. The following example returns the number of Months difference from two Dates. Here is an example of Swift and Android. getDifferenceBetweenTwoDatesInMonths(date1: Date(), date2: date!) method is define in the LIDateUtility & LIDateUtil class for Swift & Android.

*Swift

var component = DateComponents()
component.day = 12
component.month = 3
component.year = 2020
let date = Calendar.current.date(from: component)

let differenceInMonths = LIDateUtility.getDifferenceBetweenTwoDatesInMonths(date1: Date(), date2: date!)
print("Difference of months: \(differenceInMonths)")

public static func getDifferenceBetweenTwoDatesInMonths(date1: Date, date2: Date) -> Int{
    let months = Calendar.current.dateComponents([.month], from: date1, to: date2)
    return months.month ?? 0
}
*Android

Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR,1990);
calendar.set(Calendar.MONTH,9);
calendar.set(Calendar.DATE,21);
int diffMonths = LIDateUtil.getDifferenceBetweenTwoDatesInMonths(calendar.getTime(),new Date());
Log.d(TAG, "Diffrence of months = "+diffMonths)

public static int getDifferenceBetweenTwoDatesInMonths(Date fromDate, Date toDate) {
    return Math.abs((int) ((toDate.getTime() - fromDate.getTime()) / (1000 * 60 * 60 * 24)/30));
}

17) Get Difference between Two Dates in Years

This function returns the number of Years difference from two Dates. Here is an example of Swift and Android. getDifferenceBetweenTwoDatesInYears(date1: Date, date2: Date) method is define in the LIDateUtilityLIDateUtil class for Swift & Android.

*Swift

var component = DateComponents()
component.day = 12
component.month = 3
component.year = 2020
let date = Calendar.current.date(from: component)

let differenceInYears = LIDateUtility.getDifferenceBetweenTwoDatesInYears(date1: Date(), date2: date!)
print("Difference of years: \(differenceInYears)")

public static func getDifferenceBetweenTwoDatesInYears(date1: Date, date2: Date) -> Int{
        let years = Calendar.current.dateComponents([.year], from: date1, to: date2)
        return years.year ?? 0
}
*Android

Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR,1990);
calendar.set(Calendar.MONTH,9);
calendar.set(Calendar.DATE,21);
int diffYears = LIDateUtil.getDifferenceBetweenTwoDatesInYears(calendar.getTime(),new Date());
Log.d(TAG, "Diffrence of Years = "+diffYears);

public static int getDifferenceBetweenTwoDatesInYears(Date fromDate, Date toDate) {
    return Math.abs((int) getYearFromDate(toDate)-getYearFromDate(fromDate));
}

18) Get Difference between Two Dates in Hours

This function returns the number of hours difference from two Dates. Here is an example of Swift and Android. getDifferenceBetweenTwoDatesInHours(date1: Date, date2: Date) method is defined in the LIDateUtility & LIDateUtil class for Swift & Android.

*Swift

var component = DateComponents()
component.day = 12
component.month = 3
component.year = 2020
let date = Calendar.current.date(from: component)

let differenceInHours = LIDateUtility.getDifferenceBetweenTwoDatesInHours(date1: Date(), date2: date!)
print("Difference of hours: \(differenceInHours)")

public static func getDifferenceBetweenTwoDatesInHours(date1: Date, date2: Date) -> Int{
    let hours = Calendar.current.dateComponents([.hour], from: date1, to: date2)
    return hours.hour ?? 0
}
*Android

Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR,1990);
calendar.set(Calendar.MONTH,9);
calendar.set(Calendar.DATE,21);
int diffHours = LIDateUtil.getDifferenceBetweenTwoDatesInHours(calendar.getTime(),new Date());
Log.d(TAG, "Diffrence of Hours = "+diffHours);

public static int getDifferenceBetweenTwoDatesInHours(Date fromDate, Date toDate) {
    return Math.abs((int) ((toDate.getTime() - fromDate.getTime()) / (1000 * 60 * 60)));
}

19) Get Difference between Two Dates in Minutes

This function returns the number of minutes difference from two Dates. Here is an example of Swift and Android. getDifferenceBetweenTwoDatesInMinutes(date1: Date(), date2: date!) method is defined in the LIDateUtility & LIDateUtil class for Swift & Android.

*Swift

var component = DateComponents()
component.day = 12
component.month = 3
component.year = 2020
let date = Calendar.current.date(from: component)
let differenceInMinutes = LIDateUtility.getDifferenceBetweenTwoDatesInMinutes(date1: Date(), date2: date!)
print("Difference of minutes: \(differenceInMinutes)")

public static func getDifferenceBetweenTwoDatesInMinutes(date1: Date, date2: Date) -> Int{
    let minutes = Calendar.current.dateComponents([.minute], from: date1, to: date2)
    return minutes.minute ?? 0
}
*Android

Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR,1990);
calendar.set(Calendar.MONTH,9);
calendar.set(Calendar.DATE,21);
int diffMinutes = LIDateUtil.getDifferenceBetweenTwoDatesInMinutes(calendar.getTime(),new Date());
Log.d(TAG, "Diffrence of Minutes = "+diffMinutes);

public static int getDifferenceBetweenTwoDatesInMinutes(Date fromDate, Date toDate) {
    return Math.abs((int) ((toDate.getTime() - fromDate.getTime()) / (1000 * 60)));
}

20) Get Difference between Two Dates in Seconds

This function returns the number of Seconds difference from two Dates. Here is an example of Swift and Android. getDifferenceBetweenTwoDatesInSeconds(date1: Date(), date2: date!) method is defined in the LIDateUtility & LIDateUtil class for Swift & Android.

*Swift

var component = DateComponents()
component.day = 12
component.month = 3
component.year = 2020
let date = Calendar.current.date(from: component)
let differenceInSeconds = LIDateUtility.getDifferenceBetweenTwoDatesInSeconds(date1: Date(), date2: date!)
print("Difference of seconds: \(differenceInSeconds)")

public static func getDifferenceBetweenTwoDatesInSeconds(date1: Date, date2: Date) -> Int{
    let seconds = Calendar.current.dateComponents([.second], from: date1, to: date2)
    return seconds.second ?? 0
}
*Android

Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR,1990);
calendar.set(Calendar.MONTH,9);
calendar.set(Calendar.DATE,21);nTwoDatesInSeconds(date1: Date(), date2: date!)
int diffSeconds = LIDateUtil.getDifferenceBetweenTwoDatesInSeconds(calendar.getTime(),new Date());
Log.d(TAG, "Diffrence of seconds = "+diffSeconds);

public static int getDifferenceBetweenTwoDatesInSeconds(Date fromDate, Date toDate) {
    return Math.abs((int) ((toDate.getTime() - fromDate.getTime()) / (1000)));
}

21) Add number of days to date

This function returns a new Date after adding number of Days in given Date. Here is an example of Swift and Android. addNumberOfDaysToDate(date: Date(), count: 4) method is defined in the LIDateUtility & LIDateUtil class for Swift & Android.

*Swift

let newDate = LIDateUtility.addNumberOfDaysToDate(date: Date(), count: 4)
print("Date by adding days: \(newDate)")

public static func addNumberOfDaysToDate(date: Date, count: Int) -> Date{
    let newComponent = DateComponents(day: count)
    guard let newDate = Calendar.current.date(byAdding: newComponent, to: date) else {
        return date
    }
    return newDate
}
*Android

Date date = LIDateUtil.addNumberOfDaysToDate(new Date(),19);
Log.d(TAG, "Date by adding days = "+date);

public static Date addNumberOfDaysToDate(Date date, int noOfDays) {
    Calendar c = getCalender(date);
    c.add(Calendar.DATE, noOfDays);
    return c.getTime();
}

22) Add number of Months to Date

This function returns a new Date after adding number of Months in given Date. Here is an example of Swift and Android. addNumberOfMonthsToDate(date: Date(), count: 7) method is defined in the LIDateUtility & LIDateUtil class for Swift & Android.

*Swift

let newDate = LIDateUtility.addNumberOfMonthsToDate(date: Date(), count: 7)
print("Date by adding months: \(newDate)")

public static func addNumberOfMonthsToDate(date: Date, count: Int) -> Date{
    let newComponent = DateComponents(month: count)
    guard let newDate = Calendar.current.date(byAdding: newComponent, to: date) else {
        return date
    }
    return newDate
}
*Android

Date date = LIDateUtil.addNumberOfMonthsToDate(new Date(),12);
Log.d(TAG, "Date by adding months = "+date);

public static Date addNumberOfMonthsToDate(Date date, int month) {
    Calendar calendar = getCalender(date);
    calendar.add(Calendar.MONTH, month);
    return calendar.getTime();
}

23) Add number of Years to Date

This function returns a new Date after adding number of Years in given Date. Here is an example of Swift and Android. addNumberOfYearsToDate(date: Date(), count: 2) method is defined in the LIDateUtility & LIDateUtil class for Swift & Android.

*Swift

let newDate = LIDateUtility.addNumberOfYearsToDate(date: Date(), count: 2)
print("Date by adding years: \(newDate)")

public static func addNumberOfYearsToDate(date: Date, count: Int) -> Date{
    let newComponent = DateComponents(year: count)
    guard let newDate = Calendar.current.date(byAdding: newComponent, to: date) else {
        return date
    }
    return newDate
}
*Android

Date date  = LIDateUtil.addNumberOfYearsToDate(new Date(),6);
Log.d(TAG, "Date by adding years = "+date);

public static Date addNumberOfYearsToDate(Date date, int year) {
    Calendar calendar = getCalender(date);
    calendar.add(Calendar.YEAR, year);
    return calendar.getTime();
}

24) Add number of Hours to Date

This function returns a new Date after adding number of Hours in given Date. Here is an example of Swift and Android. addNumberOfHoursToDate(date: Date(), count: 5) method is defined in the LIDateUtility & LIDateUtil class for Swift & Android.

*Swift

let newDate = LIDateUtility.addNumberOfHoursToDate(date: Date(), count: 5)
print("Date by adding hours: \(newDate)")

public static func addNumberOfHoursToDate(date: Date, count: Int) -> Date{
    let newComponent = DateComponents(hour: count)
    guard let newDate = Calendar.current.date(byAdding: newComponent, to: date) else {
        return date
    }
    return newDate
}
*Android

Date date = LIDateUtil.addNumberOfHoursToDate(new Date(),17);
Log.d(TAG, "Date by adding hours = "+date);

public static Date addNumberOfHoursToDate(Date date, int hour) {
    Calendar calendar = getCalender(date);
    calendar.add(Calendar.HOUR, hour);
    return calendar.getTime();
}

25) Add number of Minutes to Date

This function returns a new Date after adding number of Minutes in given Date. Here is an example of Swift and Android. addNumberOfMinutesToDate(date: Date(), count: 60) Method is defined in the LIDateUtility & LIDateUtil class for Swift & Android.

*Swift

let newDate = LIDateUtility.addNumberOfMinutesToDate(date: Date(), count: 60)
print("Date by adding minutes: \(newDate)")

public static func addNumberOfMinutesToDate(date: Date, count: Int) -> Date{
    let newComponent = DateComponents(minute: count)
    guard let newDate = Calendar.current.date(byAdding: newComponent, to: date) else {
        return date
    }
    return newDate
}
*Android

Date date = LIDateUtil.addNumberOfMinutesToDate(new Date(),200);
Log.d(TAG, "Date by adding minutes = "+date)

public static Date addNumberOfMinutesToDate(Date date, int minutes) {
    Calendar calendar = getCalender(date);
    calendar.add(Calendar.MINUTE, minutes);
    return calendar.getTime();
}

26) Add number of Seconds to Date

This function returns a new Date after adding number of Seconds in given Date. Here is an example of Swift and Android. addNumberOfSecondsToDate(date: Date(), count: 60) method is defined in the LIDateUtility & LIDateUtil class for Swift & Android.

*Swift

let newDate = LIDateUtility.addNumberOfSecondsToDate(date: Date(), count: 60)
print("Date by adding seconds: \(newDate)")

public static func addNumberOfSecondsToDate(date: Date, count: Int) -> Date{
    let newComponent = DateComponents(second: count)
    guard let newDate = Calendar.current.date(byAdding: newComponent, to: date) else {
        return date
    }
    return newDate
}
*Android

Date date  = LIDateUtil.addNumberOfSecondsToDate(new Date(),898);
Log.d(TAG, "Date by adding seconds = "+date);

public static Date addNumberOfSecondsToDate(Date date, int seconds) {
    Calendar calendar = getCalender(date);
    calendar.add(Calendar.SECOND, seconds);
    return calendar.getTime();
}

27) Subtract(Minus) number of Days from Date

This function returns a new Date after Subtract(Minus) number of Days in given Date. Here is an example of Swift and Android. subtractNumberOfDaysFromDate(date: Date(), count: 6) Method is defined in the LIDateUtility & LIDateUtil class for Swift & Android.

*Swift

let newDate = LIDateUtility.subtractNumberOfDaysFromDate(date: Date(), count: 6)
print("Date by subtracting days: \(newDate)")

public static func subtractNumberOfDaysFromDate(date: Date, count: Int) -> Date{
    let countMinus = count * (-1)
    let newComponent = DateComponents(day: countMinus)
    guard let newDate = Calendar.current.date(byAdding: newComponent, to: date) else {
        return date
    }
    return newDate
}
*Android

Date date = LIDateUtil.subtractNumberOfDaysToDate(new Date(),19);
Log.d(TAG, "Date by subtract days = "+date);

public static Date subtractNumberOfDaysToDate(Date date, int noOfDays) {
    Calendar calendar = getCalender(date);
    calendar.add(Calendar.DATE, -noOfDays);
    return calendar.getTime();
}

28) Subtract(Minus) number of Months from Date

This function returns a new Date after Subtract(Minus) number of Months in given Date. Here is an example of Swift and Android. subtractNumberOfMonthsFromDate(date: Date(), count: 4) Method is defined in the LIDateUtility & LIDateUtil class for Swift & Android.

*Swift

let newDate = LIDateUtility.subtractNumberOfMonthsFromDate(date: Date(), count: 4)
print("Date by subtracting months: \(newDate)")

public static func subtractNumberOfMonthsFromDate(date: Date, count: Int) -> Date{
    let countMinus = count * (-1)
    let newComponent = DateComponents(month: countMinus)
    guard let newDate = Calendar.current.date(byAdding: newComponent, to: date) else {
        return date
    }
    return newDate
}
*Android

Date date = LIDateUtil.subtractNumberOfMonthsToDate(new Date(),12);
Log.d(TAG, "Date by subtract months = "+date);

public static Date subtractNumberOfMonthsToDate(Date date, int month) {
    Calendar calendar = getCalender(date);
    calendar.add(Calendar.MONTH, -month);
    return calendar.getTime();
}

29) Subtract(Minus) number of Years from Date

This function returns a new Date after Subtract(Minus) number of Years in given Date. Here is an example of Swift and Android. subtractNumberOfYearsFromDate(date: Date(), count: 10) Method is defined in the LIDateUtility & LIDateUtil class for Swift & Android.

*Swift

let newDate = LIDateUtility.subtractNumberOfYearsFromDate(date: Date(), count: 10)
print("Date by subtracting years: \(newDate)")

public static func subtractNumberOfYearsFromDate(date: Date, count: Int) -> Date{
    let countMinus = count * (-1)
    let newComponent = DateComponents(year: countMinus)
    guard let newDate = Calendar.current.date(byAdding: newComponent, to: date) else {
        return date
    }
    return newDate
}
*Android

Date date  = LIDateUtil.subtractNumberOfYearsToDate(new Date(),6);
Log.d(TAG, "Date by subtract years = "+date);

public static Date subtractNumberOfYearsToDate(Date date, int year) {
    Calendar calendar = getCalender(date);
    calendar.add(Calendar.YEAR, -year);
    return calendar.getTime();
}

30) Subtract(Minus) number of Hours from Date

This function returns a new Date after Subtract(Minus) number of Hours in given Date. Here is an example of Swift and Android. subtractNumberOfHoursFromDate(date: Date(), count: 4) Method is defined in the LIDateUtility & LIDateUtil class for Swift & Android.

*Swift

let newDate = LIDateUtility.subtractNumberOfHoursFromDate(date: Date(), count: 4)
print("Date by subtracting hours: \(newDate)")

public static func subtractNumberOfHoursFromDate(date: Date, count: Int) -> Date{
    let countMinus = count * (-1)
    let newComponent = DateComponents(hour: countMinus)
    guard let newDate = Calendar.current.date(byAdding: newComponent, to: date) else {
        return date
    }
    return newDate
}
*Android

Date date  = LIDateUtil.subtractNumberOfHoursToDate(new Date(),17);
Log.d(TAG, "Date by subtract hours = "+date);

public static Date subtractNumberOfHoursToDate(Date date, int hour) {
    Calendar calendar = getCalender(date);
    calendar.add(Calendar.HOUR, -hour);
    return calendar.getTime();
}

31) Subtract(Minus) number of Minutes from Date

This function returns a new Date after Subtract(Minus) number of Minutes in given Date. Here is an example of Swift and Android. subtractNumberOfMinutesFromDate(date: Date(), count: 60) Method is defined in the LIDateUtility & LIDateUtil class for Swift & Android.

*Swift

let newDate = LIDateUtility.subtractNumberOfMinutesFromDate(date: Date(), count: 60)
print("Date by subtracting minutes: \(newDate)")

public static func subtractNumberOfMinutesFromDate(date: Date, count: Int) -> Date{
    let countMinus = count * (-1)
    let newComponent = DateComponents(minute: countMinus)
    guard let newDate = Calendar.current.date(byAdding: newComponent, to: date) else {
        return date
    }
    return newDate
}
*Android

Date date  = LIDateUtil.subtractNumberOfMinutesToDate(new Date(),200);
Log.d(TAG, "Date by subtract minutes = "+date);

public static Date subtractNumberOfMinutesToDate(Date date, int minutes) {
    Calendar calendar = getCalender(date);
    calendar.add(Calendar.MINUTE, -minutes);
    return calendar.getTime();
}

32) Subtract(Minus) number of Seconds from Date

This function returns a new Date after Subtract(Minus) number of Seconds in given Date. Here is an example of Swift and Android. subtractNumberOfSecondsFromDate(date: Date(), count: 120) Method is defined in the LIDateUtility & LIDateUtil class for Swift & Android.

*Swift

let newDate = LIDateUtility.subtractNumberOfSecondsFromDate(date: Date(), count: 120)
print("Date by subtracting seconds: \(newDate)")

public static func subtractNumberOfSecondsFromDate(date: Date, count: Int) -> Date {
    let countMinus = count * (-1)
    let newComponent = DateComponents(second: countMinus)
    guard let newDate = Calendar.current.date(byAdding: newComponent, to: date) else {
        return date
    }
    return newDate
}
*Android

Date date  = LIDateUtil.subtractNumberOfSecondsToDate(new Date(),898);
Log.d(TAG, "Date by subtract seconds = "+date);

public static Date subtractNumberOfSecondsFromDate(Date date, int seconds) {
    Calendar calendar = getCalender(date);
    calendar.add(Calendar.SECOND, -seconds);
    return calendar.getTime();
}

33) Check if date is today’s date

This function returns a bool (TRUE || FALSE) if you pass Date is today’s date then it is return TRUE, if you pass Date which in not today then is it returns FALSE. Here is an example of Swift and Android. isToday(date: date) Method is defined in the LIDateUtility & LIDateUtil class for Swift & Android.

*Swift

var component = DateComponents()
component.day = 12
component.month = 3
component.year = 2020
let date = Calendar.current.date(from: component)

let isToday = LIDateUtility.isToday(date: date)
If isToday{
    print(“The date: \(date) is today’s date”)
}else{
    print(“The date: \(date) is not today’s date”)
}
public static func isToday(date: Date) -> Bool{
    let today = Calendar.current.component(.day, from: Date())
    let dayToCompare = Calendar.current.component(.day, from: date)
    return today == dayToCompare
}
*Android

Date date = new Date();
if (LIDateUtil.isToday(date)){
    Log.d(TAG, "the date "+date+" is today's date: ");
}else {
    Log.d(TAG, "the date "+date+" is not today's date: ");
}

public static boolean isToday(Date date) {
    Calendar calendar = getCalender(date);
    Calendar today = Calendar.getInstance();
    return (calendar.get(Calendar.YEAR) == today.get(Calendar.YEAR) && calendar.get(Calendar.MONTH) == today.get(Calendar.MONTH) && calendar.get(Calendar.DATE) == today.get(Calendar.DATE));
}

34) Check if Week Day of Date is Weekend

This function is to check if the Date is weekend or not. It will return TRUE or FALSE. Here is an example of Swift and Android. isWeekEnd(date: date) method is defined in the LIDateUtility & LIDateUtil class for Swift & Android.

*Swift

var component = DateComponents()
component.day = 12
component.month = 3
component.year = 2020
let date = Calendar.current.date(from: component)

let isWeekend = LIDateUtility.isWeekEnd(date: date)
If isWeekend{
    print(“The weekday of date: \(date) is weekend”)
}else{
    print(“The weekday of date: \(date) is not weekend”)
}
public static func isWeekEnd(date: Date) -> Bool{
        return Calendar.current.isDateInWeekend(date)
}
*Android

Date date = new Date();
if (LIDateUtil.isWeakend(date)){
    Log.d(TAG, "The weekday of date:"+date+" is weekend");
}else {
    Log.d(TAG, "The weekday of date:"+date+" is not weekend");
}

public static boolean isWeakend(Date date) {
    Calendar c = getCalender(date);
    if (c.get(Calendar.DAY_OF_WEEK) == SUNDAY || c.get(Calendar.DAY_OF_WEEK) == SATURDAY)
        return true;
    else return false;
}

35) Convert Local Time to UTC Time

This function returns the Date in UTC Date Time from Local Date Time, which means local Date to UTC Date with TimeZone Zero. Here is an example of Swift and Android. convertLocalTimeToUTC(date: Date()) Method is defined in the LIDateUtility & LIDateUtil class for Swift & Android.

*Swift

if let utcDate = LIDateUtility.convertLocalTimeToUTC(date: Date()){
    print("Local: \(Date()) || UTC: \(utcDate)")
}else{
    print("Local to UTC: Can't convert")
}
public static func convertLocalTimeToUTC(date: Date) -> Date? {
    let formatter = DateFormatter()
    formatter.dateFormat = "dd-MM-yyyy HH:mm:ss"
    let convertedString = formatter.string(from: date)
    formatter.timeZone = TimeZone(identifier: "UTC")
    return formatter.date(from: convertedString)
}
*Android

String date =  LIDateUtil.convertLocalTimeToUTC(new Date(),LIDateUtil.DEFAULT_UTC_FORMAT);
Log.d(TAG, "Local to UTC: " + date);

public static String convertLocalTimeToUTC(Date datesToConvert, String outPutFormat) {
    SimpleDateFormat dateFormater = new SimpleDateFormat(outPutFormat);
    dateFormater.setTimeZone(TimeZone.getTimeZone("UTC"));
    return dateFormater.format(datesToConvert);
}

36) Convert UTC Time to Local Time

This function returns the Date in Local Date Time from UTC Date Time, which means UTC Date to Local Date with TimeZone local. Here is an example of Swift and Android as well. convertUTCTimeToLocal(date: utcdate) Method is defined in the LIDateUtility & LIDateUtil class for Swift & Android..

*Swift

if let utcdate = formatter.date(from: "11-03-2019 16:20:28"){
    if let localDate = LIDateUtility.convertUTCTimeToLocal(date: utcdate){
        print("UTC: \(utcdate) || Local: \(localDate)")
    }
    else{
        print("UTC to Local: Can't convert")
    }
}

public static func convertUTCTimeToLocal(date: Date) -> Date? {
    let formatter = DateFormatter()
    formatter.dateFormat = "dd-MM-yyyy HH:mm:ss"
    formatter.timeZone = TimeZone(identifier: "UTC")
    let convertedString = formatter.string(from: date)
    formatter.timeZone = TimeZone.current
    return formatter.date(from: convertedString)
}
*Android

Date date =  LIDateUtil.convertUTCTimeToLocal("12/12/2019 05:10:50","dd/MM/yyyy HH:mm:ss");
Log.d(TAG, "UTC To Local Date : " + date);

public static Date convertUTCTimeToLocal(String datesToConvert, String inputFormat) {
    String dateToReturn = datesToConvert;
    SimpleDateFormat dateFormater = new SimpleDateFormat(inputFormat);
    dateFormater.setTimeZone(TimeZone.getTimeZone("UTC"));
    Date gmt = null;
    SimpleDateFormat dateFormaterOutPut = new SimpleDateFormat(inputFormat);
    dateFormaterOutPut.setTimeZone(TimeZone.getDefault());
    try {
        gmt = dateFormater.parse(datesToConvert);
        dateToReturn = dateFormaterOutPut.format(gmt);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return getDateFromString(dateToReturn, inputFormat);
}

37) Get Current TimeZone

This function will return the user’s current TimeZone. So here is an example of Swift and Android. getCurrentTimeZone() method is defined in the LIDateUtility & LIDateUtil class for Swift & Android.

*Swift

let timeZone = LIDateUtility.getCurrentTimeZone()
print(“Current timezone: \(timeZone)”)

public static func getCurrentTimeZone() -> TimeZone{
    return TimeZone.current
}
*Android

Log.d(TAG, "Current TimeZone : "+LIDateUtil.getCurrentTimezone());

public static TimeZone getCurrentTimeZone() {
    return TimeZone.getDefault();
}

38) Get TimeZone from Identifier

This function also returns the TimeZone from identifier of the TimeZone. Here is an example of Swift and Android.  getTimeZoneBy(id: “America/Los_Angeles”) method is defined in the LIDateUtilityLIDateUtil class for Swift & Android.

*Swift

if let timeZone = LIDateUtility.getTimeZoneBy(id: "America/Los_Angeles"){
    print("TimeZone by Id: \(timeZone.identifier)")
}else{
    print("TimeZone by Id: Incorrect Id")
}

public static func getTimeZoneBy(id: String) -> TimeZone?{
    return TimeZone(identifier: id)
}
*Android

TimeZone timeZone = LIDateUtil.getTimeZoneById("Asia/Kolkata");
Log.d(TAG, "TimeZone"+timeZone);

public static TimeZone getTimeZoneById(String id) {
    return TimeZone.getTimeZone(id);
}

Download IOS Swift Example Code from GitHub

IOS

Download Android Example Code from GitHub

Free SEO Checker |
Test your website for free with OnAirSEO.com

Get Your SEO report!

Don’t miss the next post!

Loading

Related Posts