Categories
scala

How to get previous dates using scala

In this post, we will see how to get previous dates using scala.

Scala program – method 1

ZonedDateTime and ZoneId – to get the date and time based on the specific zone id which we prefers to 

DateTimeFormatter – to convert the date and time to a specific format

minusDays function helps us to get the previous dates using scala as below.

import java.time.{ZonedDateTime, ZoneId}
import java.time.format.DateTimeFormatter

object PreviousDate {
  def main(arr: Array[String]): Unit = {
    val previousday = ZonedDateTime.now(ZoneId.of("UTC")).minusDays(1)
    val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm'Z'")
    val result = formatter format previousday
    println(result)
  }
}
2021-10-01T05:21Z

Scala program – method 2

object YesterdayDate {
  def main(arr: Array[String]): Unit = {
    val today = java.time.LocalDate.now
    val yesterday_date= java.time.LocalDate.now.minusDays(1)
    println(today)
    println(yesterday_date)

  }
}
2021-10-02
2021-10-01

Scala program – method 3

import java.util._
import java.lang._
import java.io._
import java.time.Instant
import java.time.temporal.ChronoUnit


object YesterdayDate {
  def main(arr: Array[String]): Unit = {
    val now = Instant.now
    val yesterday = now.minus(1, ChronoUnit.DAYS)
    System.out.println(now)
    System.out.println(yesterday)
  }
}
2021-10-02T06:37:11.695Z
2021-10-01T06:37:11.695Z

https://github.com/ushanan/SparkFirstProject/blob/master/src/main/scala/com/firstscala/spark/YesterdayDate.scala

Categories
date java

change timezone of date in java

In this post, we will learn to change timezone of date in java

In java by default new Date() will give you the system/server timezone.

Syntax
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Example

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

public class ChangeTimeZon {

	public static void main(String[] args) {
		try {
			Date date = new Date();
			System.out.println("Current Date Time : " + date);
			DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
			// In below line we are mentioned to convert into UTC
			dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
			String utcFormat = dateFormat.format(date);
			System.out.println("After converting into UTC format: " + utcFormat);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
Output
Current Date Time : Thu Jun 18 15:29:35 IST 2020
After converting into UTC format: 2020-06-18 09:59:35 UTC
Conclusion

In the above post, we learned to change timezone of date in java

Github

https://github.com/rkumar9090/BeginnersBug/blob/master/BegineersBug/src/com/geeks/example/date/ChangeTimeZon.java

Related Articles

calculate number days between two dates using java

Categories
pyspark

how to add/subtract months to the date in pyspark

In this post, We will learn how to add/subtract months to the date in pyspark with examples.

Creating dataframe – Sample program

With the following program , we first create a dataframe df with dt as of its column populated with date value '2019-02-28'

import findspark
findspark.init()
from pyspark import SparkContext,SparkConf
from pyspark.sql.functions import *
sc=SparkContext.getOrCreate()
#Creating a dataframe df with date column
df=spark.createDataFrame([('2019-02-28',)],['dt'])
print("Printing df below")
df.show()
Output

The dataframe is created with the date value as below .

Printing df below
+----------+
|        dt|
+----------+
|2019-02-28|
+----------+
Adding months – Sample program

In the Next step , we will create another dataframe df1 by adding  months to the column dt using add_months() 

date_format() helps us to convert the string '2019-02-28' into date by specifying the date format within the function .

You could get to know more about the date_format() from https://beginnersbug.com/how-to-change-the-date-format-in-pyspark/

#Adding the months 
df1=df.withColumn("months_add",add_months(date_format('dt','yyyy-MM-dd'),1))
print("Printing df1 below")
Output

add_months(column name , number of months ) requires two inputs – date column to be considered and the number of months to be incremented or decremented 

Printing df1 below
+----------+----------+
|        dt|months_add|
+----------+----------+
|2019-02-28|2019-03-31|
+----------+----------+
Subtracting months – Sample program

We can even decrement the months by giving the value negatively

#Subtracting the months 
df2=df.withColumn("months_sub",add_months(date_format('dt','yyyy-MM-dd'),-1))
print("Printing df2 below")
Output

Hence we get the one month back date using the same function .

Printing df2 below
+----------+----------+
|        dt|months_sub|
+----------+----------+
|2019-02-28|2019-01-31|
+----------+----------+
Reference

https://spark.apache.org/docs/2.2.0/api/python/pyspark.sql.html#pyspark.sql.functions.add_months

from_unixtime in pyspark with example

Categories
date java

calculate number days between two dates using java

In this tutorial, we will learn about calculate number days between two dates using java

There are lot of ways to calculate number of days between two dates in java

Using Java 8

In below example, we are going to use ChronoUnit to calculate days between two days

Syntax
ChronoUnit.DAYS.between(startDate, endDate);
Example

import java.time.LocalDate;
import java.time.Month;
import java.time.temporal.ChronoUnit;

public class CalculateDaysBetweenDatesJava8 {

	public static void main(String[] args) {
		try {
			// Start date is 2020-03-01 (YYYY-MM-dd)
			LocalDate startDate = LocalDate.of(2020, Month.MARCH, 1);

			// end date is 2020-03--03 (YYYY-MM-dd)
			LocalDate endDate = LocalDate.of(2020, Month.MARCH, 3);

			long numberOfDays = ChronoUnit.DAYS.between(startDate, endDate);

			System.out.println("Number of days " + numberOfDays);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
Output
Number of days 2

Above example is easiest way to calculate days between two dates

Int the below example we are going to use traditional way to calculate days between two days

Below Java 8

In below example we are going to use GregorianCalendar to calculate number of days between two dates

Example

import java.util.Calendar;
import java.util.GregorianCalendar;

public class CalculateDaysUsingCalender {

	public static void main(String[] args) {
		try {
			Calendar startDate = new GregorianCalendar();
			Calendar endDate = new GregorianCalendar();

			// Start date is 2020-03-01 (YYYY-MM-dd)
			startDate.set(2020, 03, 1);

			// end date is 2020-03--03 (YYYY-MM-dd)
			endDate.set(2020, 03, 3);

			// subtract emdTime-StartTime and divide by (1000 * 60 * 60 * 24)
			int i = (int) ((endDate.getTime().getTime() - startDate.getTime().getTime()) / (1000 * 60 * 60 * 24));
			System.out.println("Number of days " + i);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
Output
Number of days 2
Github

https://github.com/rkumar9090/BeginnersBug/blob/master/BegineersBug/src/com/geeks/example/CalculateDaysUsingCalender.java

https://github.com/rkumar9090/BeginnersBug/blob/master/BegineersBug/src/com/geeks/example/CalculateDaysBetweenDatesJava8.java

Related Articles

convert String to date in java with example

compare two dates in java example

Categories
pyspark

How to change the date format in pyspark

In this post, We will learn how to change the date format in pyspark

Creating dataframe

Inorder to understand this better , We will create a dataframe having date  format as yyyy-MM-dd  .

Note: createDataFrame – underlined letters need to be in capital

#Importing libraries required
import findspark
findspark.init()
from pyspark import SparkContext,SparkConf
from pyspark.sql.functions import *

sc=SparkContext.getOrCreate()
#creating dataframe with date column
df=spark.createDataFrame([('2019-02-28',)],['dt'])
df.show()
Output

With the above code ,  a dataframe named df is created with dt as one its column as below.

+----------+
|        dt|
+----------+
|2019-02-28|
+----------+
Changing the format

With the dataframe created from  the above code , the function date_format() is used to modify its format .

date_format(<column_name>,<format required>)

#Changing the format of the date
df.select(date_format('dt','yyyy-MM-dd').alias('new_dt')).show()
Output

Thus we convert the date format  2019-02-28 to the format 2019/02/28

+----------+
|    new_dt|
+----------+
|2019/02/28|
+----------+
Reference

https://spark.apache.org/docs/2.1.0/api/python/pyspark.sql.html#pyspark.sql.functions.date_format

how to get the current date in pyspark with example

Categories
date java

compare two dates in java example

 

In this post, we will learn to compare two dates in java example

There are multiple ways to compare two dates in java.

In the First example we will learn to compare dates using compareTo() method

While using compareTo() method we are having 3 chances of output. Below are the possible output

0 – When both the dates are equal

1 – When date 1 is greater than date 2

-1 – When date 1 is lesser than date 2

Syntax
date1.compareTo(date2)
Example

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateCompareExample {
	public static void main(String[] args) {
		try {

			String date1 = "22/02/2020";
			String date2 = "21/02/2020";
			DateFormat format = new SimpleDateFormat("DD/MM/yyyy");
			Date dateObj1 = format.parse(date1);
			Date dateObj2 = format.parse(date2);

			// If Both the date are same comparTo Method will return 0
			if (dateObj1.compareTo(dateObj2) == 0) {
				System.out.println("Both the dates are Equal !!");
			} // If date1 greater than date 2 it will return 1
			else if (dateObj1.compareTo(dateObj2) > 0) {

				System.out.println("Date 1 is greater than date 2");
			} // If date1 lesser than date 2 it will return -1
			else {
				System.out.println("Date 1 is lesser than date 2");
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
Date 1 is greater than date 2

Using equals(),after(),before()

In the above example, we learned using compareTo() method. But we can compare dates using predefined functions also.

Below example is another way to compare two dates in java 

equals() – return true if both the dates are equal

after() – return true if date 1 greater than date 2

before() – return true if date 1 lesser than date 2

Example

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateCompareExample {
	public static void main(String[] args) {
		try {

			String date1 = "20/02/2020";
			String date2 = "21/02/2020";
			DateFormat format = new SimpleDateFormat("DD/MM/yyyy");
			Date dateObj1 = format.parse(date1);
			Date dateObj2 = format.parse(date2);

			// If Both the date are same comparTo Method will return 0
			if (dateObj1.equals(dateObj2)) {
				System.out.println("Both the dates are Equal !!");
			} // If date1 greater than date 2 it will return 1
			else if (dateObj1.after(dateObj2)) {

				System.out.println("Date 1 is after than date 2");
			} // If date1 lesser than date 2 it will return -1
			else if (dateObj1.before(dateObj2)) {
				System.out.println("Date 1 is before than date 2");
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
Output
Date 1 is before than date 2
Reference

https://docs.oracle.com/javase/8/docs/api/java/util/Date.html#compareTo-java.util.Date-

Related Articles

convert String to date in java with example

Categories
date java

convert String to date in java with example

In this tutorial, we will learn to convert String to date in java with example.While we working with java this is one of the most scenario

We can easily convert String to Data using SimpleDateFormat.java. But before that we should know the date patterns which mentioned below 

Letter Component Presentation Examples
yYearYear1996; 96
MMonth in yearMonthJuly; Jul; 07
dDay in monthNumber10
aAm/pm markerTextPM
HHour in day (0-23)Number0
kHour in day (1-24)Number24
KHour in am/pm (0-11)Number0
hHour in am/pm (1-12)Number12
mMinute in hourNumber30
sSecond in minuteNumber55
SMillisecondNumber978

In this example we will convert 20/02/2020 to Date class 

Syntax
DateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/YYYY");
 simpleDateFormat.parse(dateString);
Example

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class SimpleDateFormatExample {

	public static void main(String[] args) {
		try {
			String dateString = "20/02/2020";
			DateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/YYYY");
			// Below line will convert from string to date
			Date parse = simpleDateFormat.parse(dateString);
			// The output will be like Sun Dec 29 00:00:00 IST 2019
			System.out.println(" Output :: "+parse);
		} catch (ParseException e) {
			e.printStackTrace();
		}

	}

}
Output
 Output :: Sun Dec 29 00:00:00 IST 2019
Reference

https://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html

Download

https://github.com/rkumar9090/BeginnersBug/blob/master/BegineersBug/src/com/geeks/example/SimpleDateFormatExample.java

Related Articles

print current date in java with example

compare two dates in java example

Categories
date java

add 3 days to the current date in java

In this post we will learn to add 3 days to the current date in java
While we working with dates we will come up with adding or subtracting from the current date

In Java there are lot of method for Date. So it is little bit difficult to remember all the things.

In this example we used Calendar.java and Date.java from java.util package
In below example we added 3 days

Syntax
object.add(Calendar.DAY_OF_YEAR, 1)
Example
import java.util.Calendar;
import java.util.Date;

public class AddDaysToDate {

	public static void main(String[] args) {
		try {
			Calendar calender = Calendar.getInstance();
			Date beforeAdding = calender.getTime();
			System.out.println("Printing the value before adding date ::: " + beforeAdding);

			// Adding the 3 days below
			calender.add(Calendar.DAY_OF_YEAR, 3);
			Date afterAdding = calender.getTime();
			System.out.println("Printing the value after adding date  ::: " + afterAdding);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
Output
Printing the value before adding date ::: Thu Feb 13 17:00:21 IST 2020
Printing the value after adding date  ::: Sun Feb 16 17:00:21 IST 2020
Github

https://github.com/rkumar9090/BeginnersBug/blob/master/BegineersBug/src/com/geeks/example/AddDaysToDate.java

Related Articles

convert String to date in java with example

compare two dates in java example

 

Categories
date java

print current date in java with example

print current date in java with example

In this post we will learn to print current date in java with examples
Here we used Date.java from java.util package
In this example the time zone will be your default system time zone

Example

import java.util.Date;

public class DateExample {
	   
	public static void main(String[] args) {
          Date date = new Date();
          System.out.println("Current Date : " + date);
     }
}

Output

Current Date : Mon Dec 23 21:35:59 IST 2019
Reference

https://beginnersbug.com/add-3-days-to-the-current-date-in-java/

https://github.com/rkumar9090/BeginnersBug/blob/master/BegineersBug/src/com/geeks/example/DateExample.java