Home > Back-end >  Is it possible to change the date time values dynamically while running the code in scala
Is it possible to change the date time values dynamically while running the code in scala

Time:12-27

I have a data like below:

val jsonData = "{\n  \"id\":\""   a   "\",\n  \"Category\":\"Flink\",\n  \"eventTime\":\"" dateTime "\"\n  \n}"

I also created a DateTime variable that gets the current timestamp.

val dateTime:String =DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS").format(LocalDateTime.now)  

Now I have a for loop for a creating a dataset:

for (a <- minRange to maxRange) {
      jsonData = "{\n  \"id\":\""   a   "\",\n  \"Category\":\"Flink\",\n  \"eventTime\":\"" dateTime "\"\n  \n}"
      println(jsonData)
      Thread.sleep(500)
    }  

Now what I am trying to achieve is, I want to replace the values of the eventTime attribute in the JSON data dynamically. It is the event time of the record. Time at which record arrived at the source. But, when I tried to run the sample code it gave me the output like below:

{
  "id":"10",
  "Category":"Flink",
  "eventTime":"2021-12-26 21:09:53.217"
  
}
{
  "id":"11",
  "Category":"Flink",
  "eventTime":"2021-12-26 21:09:53.217"
  
}

As we can see it is giving me the timestamp when the code ran which is correct but is it possible to get it dynamically like "eventTime":"2021-12-26 21:09:55.589", "eventTime":"2021-12-26 21:09:58.800"?

CodePudding user response:

Replacing the variable dateTime with its value should fetch you the dynamic event time.

for (a <- minRange to maxRange) {
  jsonData = "{\n  \"id\":\""   a   "\",\n  \"Category\":\"Flink\",\n  \"eventTime\":\"" DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS").format(LocalDateTime.now) "\"\n  \n}"
  println(jsonData)
  Thread.sleep(500)
}

Output:

{
  "id":"0",
  "Category":"Flink",
  "eventTime":"2021-12-26 23:03:04.609"
  
}
{
  "id":"1",
  "Category":"Flink",
  "eventTime":"2021-12-26 23:03:05.114"
  
}
{
  "id":"2",
  "Category":"Flink",
  "eventTime":"2021-12-26 23:03:05.616"
  
}
  • Related