How can I display current Timezone offset in GMT, in Elm - date

I'm stuck on getting the current Timezone offset from the Date in Elm.
Date.now
This returns
<Thu Feb 22 2018 20:42:42 GMT+0530 (India Standard Time)> as string
As I have explored in Elm's core lib of date and time, and they don't provide any direct method to fetch the current timezone offset. So what should I do?
import Html as App
import Html exposing (..)
import Date exposing (Date)
import Task
type alias Model =
Maybe Date
type Msg =
SetDate (Maybe Date)
update : Msg -> Model -> (Model, Cmd Msg)
update (SetDate date) _ =
(date, Cmd.none)
view : Model -> Html Msg
view model =
div [] [ text <| dateString model ]
dateString : Model -> String
dateString model =
case model of
Nothing -> "No date here"
Just date ->
(toString <| date)
now : Cmd Msg
now =
Task.perform (Just >> SetDate) Date.now
main : Program Never Model Msg
main =
App.program
{ init = ( Nothing, now )
, view = view
, subscriptions = always Sub.none
, update = update
}
I need this +0530 as in the float 5.5.

Elm's DateTime functions are pretty sparse at the moment, but justinmimbs Date.Extra library is my go to for this type of problem. Check it out here
You can import it as such,
import Date.Extra exposing (offsetFromUtc)
And, then where you had toString <| date change your pipeline to
date
|> offsetFromUtc
|> toString
That'll give you your offset in minutes, if you want the float value, just divide the int by 60. Simple function here to do so:
divBy60 : Int -> Float
divBy60 t =
toFloat t / 60.0
then just change your pipeline again to
date
|> offsetFromUtc
|> divBy60
|> toString

Related

Dataweave Date Formatting with Timezone

I'm trying to format a date to the following format, UTC with the Timezone Offset:
Expected:
2021-01-20T21:00:00-06:00
Actual:
2021-01-20T00:00:00-06:00
Code:
var arrivedAt = "2021-01-20T15:00:00"
var timezone = "America/Chicago"
var finalDateTime = (((arrivedAt as Date) as String {format: "yyyy-MM-dd'T'00:00:00"}) as LocalDateTime ++ (timezone as String))
I'm assuming it's due to the "00:00:00" in the format but when I try using "HH" or "hh" I'm receiivng errors.
The good news is that it's documented here https://docs.mulesoft.com/dataweave/2.3/dataweave-cookbook-change-time-zone
This example code assigns a timezone to the original date and then shift it to UTC
var arrivedAt = "2021-01-20T15:00:00"
var timezone = "America/Chicago"
var dateWithTimezone = (arrivedAt as LocalDateTime) ++ "America/Chicago"
// dateWithTimezone = "2021-01-20T15:00:00-06:00"
var dateOnUTC = dateWithTimezone >> "UTC"
// dateOnUTC = "2021-01-20T21:00:00Z"
---
dateOnUTC as String { format: "yyyy-MM-dd'T'HH:mm:ssXXX"}
NOTE: I'm not sure if the expected value is right on the question or if the example date is wrong.
It looks like you are using the incorrect data types and trying to do the date transformations as strings. That is highly unadvised. The errors are probably because a Date doesn't has a time neither a timezone.
One alternative is to treat the date time as a DateTime, to be able to use the timezone features:
%dw 2.0
output application/json
var arrivedAt = "2021-01-20T15:00:00"
var timezone = "America/Chicago"
var finalDateTime = (arrivedAt as DateTime >> timezone ) as String {format: "yyyy-MM-dd'T'HH:mm:ssZ"}
---
finalDateTime
Output
"2021-01-20T09:00:00-0600"
Actually the correct hour seems 9 instead of 21 as in your expected result. Maybe you did the timezone transformation the other way around?

How I can get the current year with the Js module of bucklescript?

I'm working on a ReasonReact project and I need to get the current year with the Js.Date module
I created a function to get a range between two years, so I need to pass the current year as the second parameter
let rangeYears = (startedYear, currentYear) =>
Belt_Array.range(startedYear, currentYear) ->
Array.to_list
|> List.map(
year => FormFieldSelect.{label: Js.Int.toString(year), value: `Int(year)}
)
You can instantiate a new Date type and use getFullYear.
let date = Js.Date.make()
let year = date->Js.Date.getFullYear
or, one-liner
let year = Js.Date.(make()->getFullYear)

Create time in future swift

I'm new to Swift and not so familiar with date and time classes. I want to make an object of type Date that refers to sometime in the future (like several hours).
I'm not sure if this is going to be a UNIX timestamp or not.
How can I do that?
Swift Date (or NSDate) is a class in the Foundation framework. According to the docs:
The Date structure provides methods for comparing dates, calculating
the time interval between two dates, and creating a new date from a
time interval relative to another date. Use date values in conjunction
with DateFormatter instances to create localized representations of
dates and times and with Calendar instances to perform calendar
arithmetic.
So you'd want to make use of the Calendar class to do date conversions. Something like this should do the job:
func getDateTimeForHoursInTheFuture(hours: Int) -> Date {
var components = DateComponents();
components.setValue(hours, for: .hour);
let date: Date = Date();
let expirationDate = Calendar.current.date(byAdding: components, to: date);
return expirationDate!;
}
Of course it can be changed to work with minutes and seconds instead of hours.
You can format the output using:
extension Date {
func toDateTimeString() -> String {
let formatter = DateFormatter();
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss";
let myString = formatter.string(from: self);
return myString;
}
}
Just call the toDateTimeString() method on the result of getDateTimeForHoursInTheFuture function.

Google script not recognising date

I'm trying to write some code to check values in a spreadsheet column to see if they are valid dates. However, even if I put in a date in a cell with the format set to date, it doesn't seem to recognise it as a date. When I debug the date objects are listed as "new Date" but if I attempt to ask Logger to getDate() I receive the following error :
TypeError: Cannot find function getDate in object Sat Jun 05 2010 01:00:00 GMT+0100 (BST). (line 15, file "myCode")
I can set my objects as dates by calling 'new Date()' which means that they are recognised as dates but this changes all the objects to dates whether they should be or not.
Here is my code:
function onMyPress(){
var sheet = SpreadsheetApp.getActive().getActiveSheet()
var myRange = sheet.getRange(2,2,8,1)
var myValues = myRange.getValues()
for (i=0; i<8; i++){
var testDate = myValues[i]
if (isDate(testDate)) {sheet.getRange(i+2,3,1,1).setValue("Date")
}
else{
sheet.getRange(i+2,3,1,1).setValue("Not Date")
}
Logger.log(testDate.getDate())
}
}
function isDate(testDate) {
if (Object.prototype.toString.call(testDate) !== "[object Date]") {
return false;
}
else {
return true;
}
}
Thanks for looking.
The problem is that getValues() returns a 2D array and you script assigns a "row" (a
JavaScript array) instead of cell value (a JavaScript string, Date, etc.) to testDate on the following line
var testDate = myValues[i]
One alternative is to replace the above code line by by something like the following:
var testDate = myValues[i][0]
assuming that your dates are on the first column.
"Cannot find function getDate in object" means that you are calling getDate() on an object that is NOT a Date object.
I am guessing "testDate" is a String object? If you step through the code, does it go into the "else" clause?
You need to:
Check that your String object contains a correctly formatted date
(which seems to be the case)
Then CONVERT it to a Date object, like this: var realDate = new Date(testDate);
See working example here:
https://jsfiddle.net/uyowax8o/
// Convert to Date object
var realDate = new Date(testDate);
// This now works
alert(realDate.getDate());

convert string to System.DateTime in F#

if I get a string from the command line and it looks like this:
'1-1-2011'
how can I convert that string to a DateTime object in F#?
Depending on your specific need, .NET's DateTime class has several static methods for converting strings to DateTime instances, these are DateTime.Parse, DateTime.ParseExact, and DateTime.TryParse and their several overloads.
#7sharp9 demonstrated the most basic way to perform date parsing, with a direct method call to DateTime.Parse. But where things get interesting in F# is with DateTime.TryParse. Whereas DateTime.Parse will throw an exception if the parse fails, the simplest overload of DateTime.TryParse has the signature string * byref<DateTime> -> bool which will return whether the parse succeeds setting the byref argument to the parsed date if true, or to it's default value (null in this case) otherwise. However, the syntax for using this in F# is cumbersome (and indeed it's not pleasant from any .NET language), so the F# language was designed with a special feature which allows a much nicer calling convention for methods like these as #Thomas Petricek pointed out.
But even F#'s (bool, result) return type pattern here is not ideal. Most of the time you don't need the default value if a parse fails. A nicer signature for DateTime.TryParse would be string -> option<DateTime>. Luckily, we can easily extend DateTime as we like:
type System.DateTime with
static member TryParseOption str =
match DateTime.TryParse str with
| true, r -> Some(r)
| _ -> None
We use the above extension like so:
match System.DateTime.TryParseOption "11/11/11" with
| Some r -> stdout.WriteLine r
| None -> stdout.WriteLine "none"
Which is more consistent with F# conventions (like List.tryFind, for example). But even this is can get "better". Notice how we are matching on the result of the try parse. Using Partial Active Patterns (of course!), we can wrap a whole class of try parses and move the match to the match case for greater flexibility. Take the following
open System
let (|DateTime|_|) str =
match DateTime.TryParse str with
| true, dt -> Some(dt)
| _ -> None
let (|Int|_|) str =
match Int32.TryParse str with
| true, num -> Some(num)
| _ -> None
let (|Float|_|) str =
match Double.TryParse str with
| true, num -> Some(num)
| _ -> None
Using these, we can write a neat little console application:
let rec loop() =
stdout.WriteLine "
Please select an option:
1) Parse something
2) Exit
"
match stdin.ReadLine() with
| Int 1 ->
stdout.WriteLine "Enter something to parse: "
match stdin.ReadLine() with
| Int num -> stdout.WriteLine("Successfully parsed int: {0}", num)
| Float num -> stdout.WriteLine("Successfully parsed float: {0}", num)
| DateTime dt -> stdout.WriteLine("Successfully parsed DateTime: {0}", dt)
| _ -> stdout.WriteLine "Parse Failed!"
loop()
| Int 2 ->
stdout.WriteLine "Now exiting"
| _ ->
stdout.WriteLine "Invalid option, please try again"
loop()
The key thing to notice is the nested match, where Int, Float, DateTime perform their try parses within the same match expression.
There are other neat applications of these active patterns too, for example, we can succinctly simultaneously filter and map a list of date strings
> ["11/23/2003"; "not a date"; "1/1/23 23:23pm"] |> Seq.choose(|DateTime|_|);;
val it : seq<DateTime> =
seq
[11/23/2003 12:00:00 AM {Date = 11/23/2003 12:00:00 AM;
Day = 23;
DayOfWeek = Sunday;
DayOfYear = 327;
Hour = 0;
Kind = Unspecified;
Millisecond = 0;
Minute = 0;
Month = 11;
Second = 0;
Ticks = 632051424000000000L;
TimeOfDay = 00:00:00;
Year = 2003;};
1/1/2023 11:23:00 PM {Date = 1/1/2023 12:00:00 AM;
Day = 1;
DayOfWeek = Sunday;
DayOfYear = 1;
Hour = 23;
Kind = Unspecified;
Millisecond = 0;
Minute = 23;
Month = 1;
Second = 0;
Ticks = 638082121800000000L;
TimeOfDay = 23:23:00;
Year = 2023;}]
To add one nice thing to what 7sharp9 wrote, if you also want to handle failures, you can write:
match System.DateTime.TryParse "1-1-2011" with
| true, date -> printfn "Success: %A" date
| false, _ -> printfn "Failed!"
This is not obvious, because the TryParse method has a byref<DateTime> as the last argument (and it is used using out in C#), but F# allows you to call the method like this.
You could do it as simply as this:
let dateTime = System.DateTime.Parse "1-1-2011"