Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Jon 47 posts 290 karma points
    Sep 03, 2018 @ 17:05
    Jon
    0

    Format dato to UTS (seconds since 1/1/1970)

    Hi all

    I want to format a datePicker date to UTS Unix time....

    @umbraco.library.FormatDateTime(minDato, "dd/MM/yyyy");
    

    I guess its something with DateAdd to do ...but there ends my ideas :-)

    var utsDato = umbraco.library.DateAdd(@minDato,"s","1/1/1970");
    

    Anyone who knows or already have done this?

    TIA

  • Kevin Jump 2341 posts 14868 karma points MVP 8x c-trib
    Sep 03, 2018 @ 17:34
    Kevin Jump
    100

    Hi Tia

    this is a bit more of a generic .net/c# question, but if you have a date time and are using .net 4.6+ you can ask for it directly.

    var date = new DateTime(2018, 9, 3);
    var offset = new DateTimeOffset(date);
    var unixTime = offset.ToUnixTimeSeconds();
    

    however if you are using a .net version eariler then .net 4.6 you have to do it a bit of a more long winded way.

    var date = new DateTime(2018, 9, 3, 18, 32, 0, DateTimeKind.Local);
    var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
    var unixDateTime = (date.ToUniversalTime() - epoch).TotalSeconds;
    

    if you need to convert your date from a string you can use DateTime.Parse and if you just want to work this out for the current time DateTime.Now will give you the date and time now

    Kevin

  • Jon 47 posts 290 karma points
    Sep 03, 2018 @ 18:31
    Jon
    0

    Hi Kevin

    It seems like that's the way to do it :-) Now I'm having problems connecting the parsed date to the unix...

    string minDato = item.UpdateDate.ToString("yyyy, MM, dd");
    string dateInput = @minDato;
    DateTime parsedDate = DateTime.Parse(dateInput);
    
    var date = new DateTime(parsedDate);
    var offset = new DateTimeOffset(date);
    var unixTime = offset.ToUnixTimeSeconds();
    

    It stops working at line "var date = new..." – and I've tried both "parsedDate", @parsedDate, "@ParcedDate"...?

    Yes I'm a newbee :-)

    Jon

  • Kevin Jump 2341 posts 14868 karma points MVP 8x c-trib
    Sep 03, 2018 @ 19:01
    Kevin Jump
    0

    Hi

    I am not sure you have to parse the date you actually have.

    have you tried just putting the date you have in the UpdateDate variable into the DateTimeOffset value ?

    var offset = new DateTimeOffset(item.UpdateDate)

    but just to be sure, try the pre .net4.6 version - just to be sure you aren't hitting an error because of your .net version so try :

    var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
    var unixDateTime = (item.UpdateDate.ToUniversalTime() - epoch).TotalSeconds;
    
Please Sign in or register to post replies

Write your reply to:

Draft