Kotlin DateTimeParseException - datetime

Getting date from https://api.spacexdata.com/v3/launches
This date have format: 2006-03-25T10:30:00+12:00.
I want convert it to "dd, mm, yyyy", but always getting error:
"java.time.format.DateTimeParseException: Text '2006-03-25T10:30:00+12:00' could not be parsed, unparsed text found at index 10"
my code:
val formatter = DateTimeFormatter.ofPattern("dd, mm, yyyy", Locale.US)
val myDate = LocalDate.parse(launchDate, formatter)
var launchDateConverted: String= myDate.toString()
i getting data at String, then i convert it to date for formatting, and after i converting date back to string thats to display at UI. i used different methods, but cannot find the correct way.
My current locale is "RU".

You do not need any formatter to parse your input string
You input string, 2006-03-25T10:30:00+12:00 is already in the default format used by OffsetDateTime#parse and therefore, you do not need to use a formatter explicitly in order to parse your input date-time string.
m specifies the minute while M specifies the month
You have wrongly used m for the month for which the symbol is M. Check the documentation page to learn more about these symbols.
Prefer u to y
y specifies the year-of-era (era is specified as AD or BC) and is always a positive number whereas u specifies the year which is a signed (+/-) number. Normally, we do not use + sign to write a positive number but we always specify a negative number with a - sign. The same rule applies for a year. As long as you are going to use a year of the era, AD (which is mostly the case), both, y and u will give you the same number. However, the difference occurs when you use a year of the era, BC e.g. the year-of-era, 1 BC is specified as year, 0; the year-of-era, 2 BC is specified as year, -1 and so on. You can understand it better with the following demo:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class Testing {
public static void main(String[] args) {
System.out.println(LocalDate.of(-1, 1, 1).format(DateTimeFormatter.ofPattern("u M d")));
System.out.println(LocalDate.of(-1, 1, 1).format(DateTimeFormatter.ofPattern("y M d")));
System.out.println(LocalDate.of(-1, 1, 1).format(DateTimeFormatter.ofPattern("yG M d")));
System.out.println();
System.out.println(LocalDate.of(0, 1, 1).format(DateTimeFormatter.ofPattern("u M d")));
System.out.println(LocalDate.of(0, 1, 1).format(DateTimeFormatter.ofPattern("y M d")));
System.out.println(LocalDate.of(0, 1, 1).format(DateTimeFormatter.ofPattern("yG M d")));
System.out.println();
System.out.println(LocalDate.of(1, 1, 1).format(DateTimeFormatter.ofPattern("u M d")));
System.out.println(LocalDate.of(1, 1, 1).format(DateTimeFormatter.ofPattern("y M d")));
System.out.println(LocalDate.of(1, 1, 1).format(DateTimeFormatter.ofPattern("yG M d")));
}
}
Output:
-1 1 1
2 1 1
2BC 1 1
0 1 1
1 1 1
1BC 1 1
1 1 1
1 1 1
1AD 1 1
Note: I've used Java to demonstrate the solution but it will also work in Kotlin.
The final solution:
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
OffsetDateTime odt = OffsetDateTime.parse("2006-03-25T10:30:00+12:00");
System.out.println(odt);
// Format it into the desired pattern
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd, MM, uuuu", Locale.US);
String formatted = dtf.format(odt);
System.out.println(formatted);
}
}
Output:
2006-03-25T10:30+12:00
25, 03, 2006
Learn more about the modern date-time API from Trail: Date Time.

Your formatter does not match the input format. Basically you need two formatters: one for input and one for output.
The format "dd, mm, yyyy" is wrong: mm stands for minute of hour, not for month. You should use "dd, MM, yyyy".
val launchDate = "2006-03-25T10:30:00+12:00"
val inputFormatter = DateTimeFormatter.ISO_DATE_TIME
val myDate = LocalDate.parse(launchDate, inputFormatter)
val outputFormatter = DateTimeFormatter.ofPattern("dd, MM, yyyy", Locale.US)
println(outputFormatter.format(myDate))

Related

Create a Julia Datetime from a TimePeriod and StartDate

I want to convert an Int64 representing the number of microseconds passed since 12:00:00 midnight, January 1, 0001 (0:00:00 UTC on January 1, 0001, in the Gregorian calendar) into a Julia datetime.
julia> time = Dates.Microsecond(6369175082331949400)
julia> Dates.format(time, "yyyymmdd HH:MM:SS.sss")
If you need a DateTime, just make sure you have your Int64 correctly in milliseconds, and you can use the (undocumented) UTInstant constructor, and then later add back the fractional microseconds (comment: your example number, 6369175082331949400, seems big for recent Gregorian time in microseconds, it may be nanoseconds):
julia> using Dates
julia> t = now().instant
Dates.UTInstant{Millisecond}(63694318624788 milliseconds)
julia> dump(t)
Dates.UTInstant{Millisecond}
periods: Millisecond
value: Int64 63694318624788
julia> t2 = Dates.UTInstant(Millisecond(63691750823319))
Dates.UTInstant{Millisecond}(63691750823319 milliseconds)
julia> DateTime(t2)
2019-04-24T01:00:23.319
julia> t3 = DateTime(t2)+ Dates.Microsecond(494)
2019-04-24T01:00:23.319
You can get what you want using Dates.epochms2datetime and applying an adjustment to it for your case as shown below.
Lets take datetime_value as the date we are interested in getting:
datetime_value = Dates.DateTime(2019,1,1,0,0,0)
date_start = Dates.DateTime(1,1,1,0,0,0)
date_diff = datetime_value - date_start
This gives you a value of 63681897600000 milliseconds for date_diff. Now Dates.epochms2datetime considers start of epoch as 0000-01-01T00:00:00. So we need to add 1 Year and 1 Day to the result after using Dates.epochms2datetime to arrive at our datetime value from the milliseconds value:
julia> Dates.epochms2datetime(63681897600000) + Dates.Year(1) + Dates.Day(1)
2019-01-01T00:00:00
I'm not sure I completely understand the question, as Dates.Microsecond merely returns the Int64 value of a Date or Time. However, you can create the DateTime value from a specific date and then work from there. Subtraction is allowed for DateTime values and it returns the difference in milliseconds.
using Dates
dateThen = DateTime(1, 1, 1, 0, 0, 0)
dateNow = now(UTC)
diff = dateNow - dateThen
dump(diff * 1000)
Int64 63694261047549000 (or whatever time you run it.)
Using some of the ideas provided, I came up with:
function convert_datetime(time)::DateTime
num = div(time, 100000)
remainder = rem(time, 100000)
time = DateTime(Dates.UTInstant(Millisecond(num))) + Dates.Day(1)
# time = Dates.epochms2datetime(trade.date_time/100000) + Dates.Year(1) + Dates.Day(1)
time + Dates.Microsecond(remainder)
end

Why incorrect convert from string to date?

In my Kotlin code:
const val TS_DATE_PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSS"
val ts = responseJsonObject.get("TS").getAsString()
val tsDate = SimpleDateFormat(TS_DATE_PATTERN).parse(ts)
val tsDateAsString = SimpleDateFormat(TS_DATE_PATTERN).format(tsDate)
logger.info("ts = " + ts + " -> tsDate = " + tsDate + " -> tsDateAsString = " + tsDateAsString)
And here the (formatted for readability) result:
ts = 2019-01-14T22:56:30.429582
tsDate = Mon Jan 14 23:03:39 EET 2019
tsDateAsString = 2019-01-14T23:03:39.582
As you can see the ts and tsDateAsString have different times, although they came from the same starting point.
E.g. ts = 22:56:30 but in tsDateAsString = 23:03:39
Why?
As a suggestion: whenever you can, use java.time-utilities.
SimpleDateFormat has a special handling for the milliseconds. Everything that is parsed by the S is treated as milliseconds. As long as you deal with 3-digit-milliseconds, everything is fine (you may even just use a single S (i.e. .S) for the milliseconds to parse them), but if you use 6-digit-milliseconds as input then you also get a 6-digit-millisecond(!)-value.
The 6-digit-milliseconds then are actually 3-digit seconds + the 3-digit milliseconds. That is where the deviation is coming from.
How to solve that? Well either shorten the input time string and lose some precision or use the preferred DateTimeFormatter instead with a pattern matching your input, i.e. yyyy-MM-dd'T'HH:mm:ss.SSSSSS:
val TS_DATE_PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSSSSS"
val formatter = DateTimeFormatter.ofPattern(TS_DATE_PATTERN)
val tsDate = formatter.parse(ts) // now the value as you would expect it...
Transforming that to a TimeStamp will work as follows:
Timestamp.valueOf(LocalDateTime.from(tsDate))

Converting a double to UTCTime

The title is all it is.
Assume I have a double:
let d = 11241241.10124012 :: Double
How do I get an instance of UTCTime corresponding to d, d as in unix seconds?
You need to convert the double to a fractional in order for it to be understood as a NominalDiffTime value (which is an instance of Fractional). Once it is understood as a NominalDiffTime value, then posixSecondsToUTCTime will handle the conversion (POSIXTime being a type synonym of NominalDiffTime).
import Data.Time.Clock
import Data.Time.Clock.POSIX(posixSecondsToUTCTime)
doubleToUTCTime d = posixSecondsToUTCTime $ realToFrac d

How to show only the whole numbers in Y number aexis in stackedbarchart/barchart

Y axis tick label should only show non decimal values / whole numbers as as series . if i set set TickUnit to 1 it should be 1,2,3,4,5,.. if i set Unit Ticks to 2 ..2,4,6,8,.. if i set to 5 5,10,15,20,25.
i set the Unit Ticks to 1 still it sometimes adding the decimal values also and showing 2.5 ,5.0,7.5,10.0,12.5......how to prevent this and show only whole numbers(Non decimal Numbers).?
option 1. store the number as an int, int num = (int)Math.floor(myDouble);
option 2. in your method make the parameter a double and inside the method cast it to an int
this will allow you to use the method with both a double and a int. Please keep in mind that this is C# code but java should be very similar.
private List<int> numberSeries(double aDouble)
{
List<int> number = new List<int>();
int base = (int)Math.floor(aDouble);
for(int x = 1;x++ < 10) //change 10 to whatever you want
{
number.Add(aDouble * x);
}
return number;
}

In Scala 2.8, how to access a substring by its length and starting index?

I've got date and time in separate fields, in yyyyMMdd and HHmmss formats respectively. To parse them I think to construct a yyyy-MM-ddTHH:mm:ss string and feed this to joda-time constructor. So I am looking to get 1-st 4 digits, then 2 digits starting from the index 5, etc. How to achieve this? List.fromString(String) (which I found here) seems to be broken.
The substring method certainly can get you there but String in Scala 2.8 also supports all other methods on sequences. The ScalaDoc for class StringOps gives a complete list.
In particular, the splitAt method comes in handly. Here's a REPL interaction which shows how.
scala> val ymd = "yyyyMMdd"
ymd: java.lang.String = yyyyMMdd
scala> val (y, md) = ymd splitAt 4
y: String = yyyy
md: String = MMdd
scala> val (m, d) = md splitAt 2
m: String = MM
d: String = dd
scala> y+"-"+m+"-"+d
res3: java.lang.String = yyyy-MM-dd
Just use the substring() method on the string. Note that Scala strings behave like Java strings (with some extra methods), so anything that's in java.lang.String can also be used on Scala strings.
val s = "20100903"
val t = s.substring(0, 4) // t will contain "2010"
(Note that the arguments are not length and starting index, but starting index (inclusive) and ending index (exclusive)).
But if this is about parsing dates, why don't you just use java.text.SimpleDateFormat, like you would in Java?
val s = "20100903"
val fmt = new SimpleDateFormat("yyyyMMdd")
val date = fmt.parse(s) // will give you a java.util.Date object
If you're using Joda Time, you should be able to use
val date = DateTimeFormat.forPattern("yyyyMMdd, HHmmss")
.parseDateTime(field1 + ", " + field2)
For the more general problem of parsing Strings like this, it can be helpful to use a Regex (although I wouldn't recommend it in this case):
scala> val Date = "(\\d\\d\\d\\d)(\\d\\d)(\\d\\d)".r
Date: scala.util.matching.Regex = (\d\d\d\d)(\d\d)(\d\d)
scala> "20100903" match {
| case Date(year, month, day) => year + "-" + month + "-" + day
| }
res1: java.lang.String = 2010-09-03
val field1="20100903"
val field2="100925"
val year = field1.substring(1,5)
val month = field1.substring(5,7)
val day = ...
...
val toYodaTime = year + "-" + month+"-"+day+ ...

Resources