java.time format date depending on locale with 2 digits day/month and 4 digits year - kotlin

I need to show a date with 2 digits day, 2 digits month, 4 digits year according to the order of the local. So for April 10th 2020 I want to show
for locale US: MM/DD/YYYY -> 04/10/2020
for locale UK: DD/MM/YYYY -> 10/04/2020
for locale DE (Germany): DD.MM.YYYY -> 10.04.2020
I tried the following without success:
// this one already fails for DE, because it gives 10.04.20 (only 2 digit years)
myDate?.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT))
// works for DE (gives 10.04.2020), fails for UK as is gives 10 Apr 2020 instead of 10/04/2020
myDate?.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM))
So, how can I get a locally adapted date format with only 2 digits day/month and 4 digits year? Please note that I am looking for a general solution, the 3 locales explicitly stated here are just examples.
I am actually using a java.time port for Android (ThreeTenABP), though this shouldn't be relevant.

I am afraid that it will take some hand work. For example, in Java because this is what I can write:
Locale formattingLocale = Locale.getDefault(Locale.Category.FORMAT);
String builtInPattern = DateTimeFormatterBuilder.getLocalizedDateTimePattern(
FormatStyle.SHORT, null, IsoChronology.INSTANCE,
formattingLocale);
String modifiedPattern = builtInPattern.replaceFirst("y+", "yyyy")
.replaceFirst("M+", "MM")
.replaceFirst("d+", "dd");
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern(modifiedPattern, formattingLocale);
LocalDate myDate = LocalDate.of(2020, Month.APRIL, 10);
System.out.println(myDate.format(dateFormatter));
Example outputs in different locales:
US: 04/10/2020
UK: 10/04/2020
Germany: 10.04.2020
Swedish/sv: 2020-04-10
Hong Kong/zh-HK: 2020年04月10日 (I got no idea whether this is correct)

Ole V.V.'s answer works from Oreo forwards, but lots of devices are using older versions of Android. The following works in most countries for all Android versions.
This looks hacky, but the official JavaDoc for DateFormat says that casting the format from factory methods to SimpleDateFormat works in majority of countries.
val dateFormat = DateFormat.getDateInstance(DateFormat.SHORT)
if (dateFormat is SimpleDateFormat) {
val adjustedPattern = dateFormat.toPattern()
.replace("y+".toRegex(), "yyyy")
.replace("M+".toRegex(), "MM")
.replace("d+".toRegex(), "dd")
dateFormat.applyPattern(adjustedPattern)
}
You may wrap that in a try-catch-block and do something clever for the few exceptional countries where this doesn't work. Or for them you could just give up and use their default short format. I'm pretty sure humans can understand that format :-D.

Related

Is there an option on KustoExplorer so I can write my dates with UK format?

Currently when I write dates in Kusto they are in USA format
//1st April 2022
let Date_USA = datetime(04-01-2022);
Is there an option in Kusto Explorer that would allow me to write dates in UK format instead?
//1st April 2022
let Date_UK = datetime(01-04-2022);
Avoid either.
The only place where you should ever use any date format other than ISO (yyyy-MM-dd) is customer facing applications.
ISO is the only format that is not open for interpretation by your software/SDK/OS and is not affected by any configuration settings.
let Date = datetime(2022-04-01);

I want to create U.S. Date Format to Indian Date Format Using Asp MVC Core 2.0

I am trying to Create Date Format the US to Indian Date Format like(dd/mm/yyyy hh:mm tt).
When I run the code on my local machine it works.
When we publish and fetch values from the server at that time it shows "US" Date Format(mm/dd/yyyy)
How τo do the internal conversion, in Appsettings.json what strings i need to mention.
public static DateTime ConvertIndianDateFormat(DateTime usTime)
{
DateTime dateTime = DateTime.Now;
TimeZoneInfo usEasternZone = TimeZoneInfo.FindSystemTimeZoneById("US Eastern Standard Time");
TimeZoneInfo indianZone = TimeZoneInfo.FindSystemTimeZoneById("India Standard Time");
DateTime usEasternTime = TimeZoneInfo.ConvertTimeFromUtc(usTime, usEasternZone);
DateTime indianTime = TimeZoneInfo.ConvertTimeFromUtc(usTime, indianZone);
return indianTime;
}
This is because you are probably using something like DateTime.Now for C# and if you have an SQL Server you are using GETDATE(). It's not like an issue with application.json or something. The above functions return the machine datetime, thus why locally on your pc the time is correct and incorrect if you upload it to a server.
So make sure that the time is correct. If you are uploading to servers in another country then you will probably have a different time and/or format.
How you proceed depends on your needs:
Is the time correct?
Then simply reformated it or store it specifically using
DateTime.Now.ToString("dd/mm/yyyy hh:mm tt") // this is not the correct format.
Do you want to serve multiple clients in multiple regions/countries?
Then you should store the time as UTC and cast it based on clients date format. For example the server could be in USA and someone from UK would view a different time than his own which would be weird.
DateTime.UtcNow
Generally your problem could be large or small depending on your needs

Convert between arbitrary timezones

I'm trying to find a simple yet robust way to convert time between arbitrary time zones.
This: http://www.cpearson.com/excel/TimeZoneAndDaylightTime.aspx explains only how to convert betwen my (current) TZ and another TZ.
Those two SO articles (Getting Windows Time Zone Information (C++/MFC) and How do you get info for an arbitrary time zone in Windows?) talk about getting the information from the registry.
That sounds a bit too convoluted and time-consuming; moreover, it appears that Windows stores TZs in their "full names" (such as (UTC-08:00) Pacific Time (US & Canada)) and I'd rather refer to TZs using abbreviations (such as EDT). Moreover, relying on Windows registry could also be unsafe: different users might have different versions and some might not be up to date. That would mean a report run by two persons might provide two different results!
Is there a simpler way that will also be robust? Writing a lookup table could work for some time but then it will be broken when a government decides to abolish DST or change anything else.
Maybe get a list of TZs from Internet and parse it? Would that be safe enough?
Update 1
I've made my research and explored the possibilities, but this problem is not as trivial as it might seem. If you think that the function shall look like bTime = aTime + 3, then please reconsider. Timezones and DSTs are in a state of constant flux.
Read this for reference: list of pending / proposed timezone changes. Note that some countries are actually changing their timezones, not just DST settings! And Brazil changed the date on which they change their clocks to winter time! A static lookup table would be broken very quickly by all those changes.
Update 2
I'm not looking into a quick and dirty hack, I can come up with that myself. I'm not wanting to write something and forget about it; I'd like to create a function once that could be safely used by other people for different internal projects without the maintenance nightmare. Hard-coding constants that are known to change once in a while is a very bad software design (think Y2K bug caused by a very, very old piece of code).
Update 3
This database looks good (although I'm not sure if it's stable enough): https://timezonedb.com/api. They even have a TZ conversion call - exactly what I need! I will probably try to parse XML from VBA and share my results.
The API at https://timezonedb.com/references/convert-time-zone is indeed a great place to get the correct worldwide time, timezone, and timezone-offset between two locations, taking into account past/future Daylight Savings changes.
A problem with your suggested method of specifying only the Time Zone Abbreviations (such as "convert PST to EST") is that this API takes your zones literally, even if they are incorrect.
So, if Toronto is currently on EDT but you specify EST, you'll probably get the incorrect time. Using "full names" like (UTC-08:00) Pacific Time (US & Canada) would have the same issue.
A way around that is to specify the time zone names like America/Vancouver (as listed here), or else specify the city, country and/or region name with the appropriate parameters.
I wrote a function to figure it out but it only applies to certain countries (see further down).
What time was it in Toronto last Halloween at 11:11pm Vancouver time?
http://api.timezonedb.com/v2/convert-time-zone?key=94RKE4SAXH67&from=America/Vancouver&to=America/Toronto&time=1509516660
Result: (Default is XML but JSON is also available.)
<result>
<status>OK</status>
<message/>
<fromZoneName>America/Vancouver</fromZoneName>
<fromAbbreviation>PDT</fromAbbreviation>
<fromTimestamp>1509516660</fromTimestamp>
<toZoneName>America/Toronto</toZoneName>
<toAbbreviation>EDT</toAbbreviation>
<toTimestamp>1509527460</toTimestamp>
<offset>10800</offset>
</result>
Getting the data programmatically:
There are plenty of options and lookup methods you will have to decide upon, but here's one example using a VBA Function:
What will be the time difference between Vancouver & Berlin on Christmas Day?
Input Time: 2018-12-25 00:00:00 = Vancouver Local Unix time 1545724800
Function GetTimeZoneOffsetHours(fromZone As String, _
toZone As String, UnixTime As Long) As Single
Const key = "94RKE4SAXH67"
Const returnField = "<offset>"
Dim HTML As String, URL As String
Dim XML As String, pStart As Long, pStop As Long
URL = "http://api.timezonedb.com/v2/convert-time-zone?key=" & key & _
"&from=" & fromZone & "&to=" & toZone & "&time=" & UnixTime
With CreateObject("MSXML2.XMLHTTP")
.Open "GET", URL, False
.Send
XML = .ResponseText
End With
pStart = InStr(XML, returnField)
If pStart = 0 Then
MsgBox "Something went wrong!"
Exit Function
End If
pStart = pStart + Len(returnField) + 1
pStop = InStr(pStart, XML, "</") - 1
GetTimeZoneOffsetHours = Val(Mid(XML, pStart, pStop - pStart)) / 60
End Function
Sub testTZ()
Debug.Print "Time Zone Offset (Vancouver to Berlin) = " & _
GetTimeZoneOffsetHours("America/Vancouver", _
"Europe/Berlin", 1545724800) & " hours"
End Sub
Unix/UTC Timestamps:
Unix time is defined as "the number of seconds that have elapsed since 00:00:00 Coordinated Universal Time (UTC), Thursday, 1 January 1970."
You can convert times between Unix and/or UTC or Local time at: epochconverter.com ... the site also has conversion formulas for several programming languages.
For example, the formua to convert Unix time to GMT/UTC in Excel is:
=(A1 / 86400) + 25569
You could also download static files (in SQL or CSV format) here instead of caling the API, and the page also has sample queries. However use caution: it's easier to make mistakes with Daylight Savings (as mentioned above).
I made a dummy account to get the "demo" used in the examples, but you should get your own (free) key for long-term use. (I'm not responsible if it gets locked out from over-use!)
An good alternative Time Zone API is Google Maps Time Zone API. The difference is that you specify Latitude & Longitude. It seems to work just fine without a key You'll need to register for a key.
What will the Time Zone Offset be on June 1st at the White House?
https://maps.googleapis.com/maps/api/timezone/json?location=38.8976,-77.0365&timestamp=1527811200&key={YourKeyHere}
Result:
{
"dstOffset" : 0,
"rawOffset" : -18000,
"status" : "OK",
"timeZoneId" : "America/Toronto",
"timeZoneName" : "Eastern Standard Time"
}
The Offset will be -18000 seconds (-5 hours).
Determining when Daylight Savings is in effect
Below is a function I put together so I could "trust" the Daylight Savings (DST) values I was getting from a different API, however (as discussed by others) the rules have no pattern plus are constantly changing country by country, even town by town in some parts of the world, so this only will work in countries where:
DST begins on the Second Sunday of March every year
DST end on the First Sunday of November every year
The applicable countries are Bahamas, Bermuda, Canada, Cuba, Haiti, St. Pierre & United States. (Source: Daylight saving time by country**)
Function IsDST(dateTime As Date) As Boolean
'Returns TRUE if Daylight Savings is in effect during the [dateTime]
'DST Start (adjust clocks forward) Second Sunday March at 02:00am
'DST end (adjust clocks backward) First Sunday November at 02:00am
Dim DSTStart As Date, DSTstop As Date
DSTStart = DateSerial(Year(dateTime), 3, _
(14 - Weekday(DateSerial(Year(dateTime), 3, 1), 3))) + (2 / 24)
DSTstop = DateSerial(Year(dateTime), 11, _
(7 - Weekday(DateSerial(Year(dateTime), 11, 1), 3))) + (2 / 24)
IsDST = (dateTime >= DSTStart) And (dateTime < DSTstop)
End Function
And a couple examples of how I could use function IsDST*:
Public Function UTCtoPST(utcDateTime As Date) As Date
'Example for 'PST' time zone, where Offset = -7 during DST, otherwise if -8
If IsDST(utcDateTime) Then
UTCtoPST = utcDateTime - (7 / 24)
Else
UTCtoPST = utcDateTime - (8 / 24)
End If
End Function
Function UTCtimestampMStoPST(ByVal ts As String) As Date
'Example for 'PST', to convert a UTC Unix Time Stamp to 'PST' Time Zone
UTCtimestampMStoPST = UTCtoPST((CLng(Left(ts, 10)) / 86400) + 25569)
End Function
* Note that function IsDST is incomplete: It does not take into account the hours just before/after IsDST takes actually effect at 2am. Specifically when, in spring, the clock jumps forward from the last instant of 01:59 standard time to 03:00 DST and that day has 23 hours, whereas in autumn the clock jumps backward from the last instant of 01:59 DST to 01:00 standard time, repeating that hour, and that day has 25 hours ...but, if someone wants to add that functionality to update the function, feel free! I was having trouble wrapping my head around that last part, and didn't immediately need that level of detail, but I'm sure others would appreciate it!
Finally one more alternative is an API that I use to for polling current/future/historical weather data for various purposes — and also happens to provide Timezone Offset — is DarkSky.
It queries by latitude/longitude and is free (up to 1000 calls/day) and provides "ultra-accurate weather data" (more-so in the USA, where it predicts weather down to the minute and to the square-yard! — but quite accurate I've seen for the unpredictable Canadian West Coast Canada!)
Response is in JSON only, and the very last line is Time Zone Offset versus UTC/GMT time.
DarkSky Sample Call:
https://api.darksky.net/forecast/85b57f827eb89bf903b3a796ef53733c/40.70893,-74.00662
It says it's supposed to rain for the next 60 hours at Stack Overflow's Head Office. ☂
...but I dunno, it looks like a pretty nice day so far! ☀
(flag)
Im afraid anything to do with timezones is never a simple task (ask any web designer and they will say it is a massive challenge)
there are 2 ways to solve your problem
1) The Easy way - Create a central list which all other workbooks are linked to. This can be saved on SharePoint or on a shared drive, then all you have to do is update this one table
2) The hard way - Use a website API to get the latest timezone data. https://www.amdoren.com/ is a good site, you can get a free API key by signing up. The only issue is you then have to parse the Json file from the website. This isn't easy but if you google "vba parse json" you will find some solutions (it generally requires importing some libraries and using other peoples code as a starting point)
Hope you find the right solution, and if you do might be worth sharing it as im sure there will be others with same issue.

Swift 3 playground logs dates in local format. How?

If you run a line like this in a Playground in the US:
let today = Date()
You'll see output like this to the right of the source code:
"Sep 26, 2016, 8:17 PM"
That appears to be the date, displayed in the local time zone, using medium date and time style.
How does that work?
If you try to print the date:
print("today = \(today)"
You'll see "Today = 2016-09-27 00:18:55 +0000\n", which is UTC, and appears to be unix date format.
What function is the Playground using to display the date when you first create a date? Is there a way to get to that output format from code or from the debug console?
Up until now I've created a date formatter that I use to log dates, display them in the console, etc.
It's lurking in CustomPlaygroundQuickLookable protocol, which Date conforms to:
if case .text(let str) = today.customPlaygroundQuickLook {
print(str)
}

Calculate end date based on # of days and start date

I am working on script where users can make certain type of orders. Now when users make an order they can choose how long they wont it to last in # of days. Once the order is placed I need to approve their order and that approval date is recorded inside my database. Now what I need is to show inside their user panel how much days their package will last since the day of my approval. So for example if I approved their order September 08, 2013 and they choosed for the order to last 7 days, I wont them to see inside they panel for every next day they login how much days they have left, so 7days, 6days, 5days, etc... all the way to "0 Days" when they come to their panel on September 16, 2013.
I have following variables for those two values:
$row_ordersResults['date'] - the date I approved the order
$row_ordersResults['drip_feed'] - # of days they wont for their order to last
I did tried to lots of combinations by myself but I am totally stuck with this and cant make it work.
Thanks for help!
The libraries at momentjs.com is pretty cool. But if you just wanted something simple to calculate the "date difference" between two time values, there is a relatively simple way to do it. I assume you wanted it done in Javascript.
All you need to do is to clear out the hour/minute/second/millisecond fields of the two dates, calculate their differences in days. Put the script below in any web browser and you'll see how it works.
<script>
function foo() {
var d1 = new Date(2013, 8, 12, 13, 40, 1, 333); // any date value, last 4 params can be anything
var d2 = new Date(2013, 9, 3, 11, 42, 32, 533);
d1.setHours(0); d1.setMinutes(0); d1.setSeconds(0); d1.setMilliseconds(0);
d2.setHours(0); d2.setMinutes(0); d2.setSeconds(0); d2.setMilliseconds(0);
daysLeft = (d2.getTime() - d1.getTime())/(24*60*60*1000);
alert('Dear customer, there is(are) ' + daysLeft + ' day(s) left on your order!' );
}
</script>
Show Remaining Days on Order
EDIT: adding PHP version
<?php
$d1 = New DateTime('2013-08-28 06:25:00');
$d2 = new DateTime(); // now
$drip = 55;
$interval = $d2->diff($d1); // time difference
$days_left = $drip - $interval->format('%a'); // in days, subtract from drip
echo "There are $days_left days left\n";
?>
I hope I don't get marked down for not suggesting a specific answer, but time and date calculations are very tedious and JavaScript's Date() provides limited options. So rather than offer some ugly code, I suggest you take a look at moment.js at momentjs.com. Once you attach the script to your pages, you can easily manage all kind of date formats, and set up a function that will allow you to do math on dates and automatically generate your date ranges - it will even let you format them in to user friendly formats like "in 3 days", which I think is what you want. If your app has anything to do with time, and most do, I can't recommend Moment highly enough.