我正在撰寫一個每月自動執行一次的代碼,它將計算機中的日期作為執行while回圈的開始和結束日期。
val today = new DateTime().withZone(DateTimeZone.forID("Asia/Kolkata"))
var start = today.toString(DateTimeFormat.forPattern("yyyy-MM-dd"))
val end = today.toString(DateTimeFormat.forPattern("yyyy-MM-dd"))
while(start<=end){
Data(start,end)
}
def Data (start: DateTime, end: DateTime) {
val start_temp = start
val end_temp = end
var start_temp_1 = start_temp.minusMonths(1).withDayOfMonth(1);
var start_date_monthly = start_temp_1.toString(DateTimeFormat.forPattern("yyyy-MM-dd"))
println("Last Month Start Date: " start_date_monthly)
var end_temp_1 = end_temp.minusMonths(0).withDayOfMonth(1);
var end_temp_2 = end_temp_1.minusDays(1)
var end_date_monthly = end_temp_2.toString(DateTimeFormat.forPattern("yyyy-MM-dd"))
println("Last Month End Date: " end_date_monthly)
}
變數中的日期today需要轉換為第一個和最后一個日期
- 上個月從
today - 當前和上一季度從
today
我能夠完成Data函式中顯示的第一個。
假設今天得到以下日期 -2022-01-27T14:25:26.374 05:30
上面的函式回傳
Last Month Start Date: 2021-12-01
Last Month End Date: 2021-12-31
我如何才能在第二個 - 當前和上一季度的第一個和最后一個日期實作這一點?
Ex - 今天得到下一個日期 -2022-01-27T14:25:26.374 05:30
我需要回傳2021-10-01上2021-12-31一季度和2022-01-01當前2022-03-31季度。
某些解決方案建議使用 Spark SQL 和 Dataframes,但這不適用于這種情況。
有沒有像月案例那樣直接做到這一點的方法?還是udf是這里唯一的選擇?
uj5u.com熱心網友回復:
以下可以做到。如果必須將其應用于 DF 中的每一行,這可能是一個 UDF
import java.time.temporal.IsoFields
import java.time.temporal.IsoFields.QUARTER_OF_YEAR
import java.time.{LocalDate, YearMonth}
def printQuarterBeginAndEnd(localDate: LocalDate): Unit = {
val currentQuarter = localDate.get(QUARTER_OF_YEAR)
val currentYear = localDate.getYear
val currentMonth = localDate.getMonth
val startOfQuarter = YearMonth.of(currentYear, currentMonth).`with`(QUARTER_OF_YEAR, currentQuarter).atDay(1)
val endOfQuarter = YearMonth.of(currentYear, currentQuarter * 3).`with`(QUARTER_OF_YEAR, currentQuarter).atEndOfMonth()
println(s"Start $startOfQuarter ends $endOfQuarter")
}
printQuarterBeginAndEnd(LocalDate.now())
printQuarterBeginAndEnd(LocalDate.now().minus(1, IsoFields.QUARTER_YEARS))
列印以下內容
import java.time.temporal.IsoFields
import java.time.temporal.IsoFields.QUARTER_OF_YEAR
import java.time.{LocalDate, YearMonth}
printQuarterBeginAndEnd: (localDate: java.time.LocalDate)Unit
Start 2022-01-01 ends 2022-03-31
Start 2021-10-01 ends 2021-12-31
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/422296.html
標籤:
