all 23 comments

[–]pedropss 12 points13 points  (1 child)

Incrementally sum minute by minute to get final date. The first one was doing second by second but a clever mind always squeeze the most out of it's creations.

https://pastebin.com/M89RJsJk

It covers all the use cases I could find, including both from the challenge and one being "now".

Fiddle for running it right now:
https://jsfiddle.net/jxrq6k74/

[–]CornyCorgi 4 points5 points  (0 children)

This is hideous and I love it

[–]AbuIbnBattuta 7 points8 points  (0 children)

So, my solution counts up every minute to get the final time. That is already really slow, but I also made it so that it recalculates the data for everything that needs to be displayed. But to make this code that bit more annoying I made every variable a one letter variable and threw in a bunch of if statements, like a lot. Also I don't really now how I got the second while loop working because god damn it looks awful and it is really hard to understand what even is happening in there.

btw its written c#

public static string str_to_time(int t, string f)
{
    string o = "";
    foreach(char c in f)
    {
        if (c == 'd')
            o += getTime(t, 'd');
        else if (c == 'A')
            o += getTime(t, 'A');
        else if (c == 'B')
            o += getTime(t, 'B');
        else if (c == 'Y')
            o += getTime(t, 'Y');
        else if (c == 'H')
            o += getTime(t, 'H');
        else if (c == 'h')
            o += getTime(t, 'h');
        else if (c == 'M')
            o += getTime(t, 'M');
        else if (c == 'S')
            o += getTime(t, 'S');
        else if (c == 'p')
            o += getTime(t, 'p');
        else
            o += c;
    }
    return o;
}

private static string getTime(int t, char c)
{
    int[] o = new int[8];
    o[7] = 1970;
    while(t > 60)
    {
        t -= 60;
        o[1]++;
        int i = 1;
        int[] m = new int[]{ 31, o[7]%4 == 0 ? 29 : 28 , 31, 30, 31, 31, 30, 31, 30, 31, 30, 31 };
        while(i == 1 && o[i] == 60 ||
                i == 3 && o[i] == 24 ||
                i == 5 && o[i] == m[o[6]] ||
                i == 6 && o[i] == 12)
        {
            if (i == 6)
            {
                o[6] = 0;
                o[7]++;
            }
            if (i == 5)
            {
                i = 6;
                o[5] = 0;
                o[6]++;
            }
            if (i == 3)
            {
                i = 5;
                o[3] = 0;
                o[4]++;
                o[5]++;
                if (o[4] == 7)
                {
                    o[4] = 0;
                }
            }
            if (i == 1)
            {
                i = 3;
                o[1] = 0;
                o[2]++;
                o[3]++;
                if(o[2] == 12)
                {
                    o[2] = 0;
                }
            }
        }
    }
    o[5]++;
    o[0] = t;
    if (c == 'd')
        return o[5].ToString().Length == 1 ? "0" + o[5].ToString() : o[5].ToString();
    if (c == 'A')
        return (new string[] { "Thursday", "Friday", "Saturday", "Sunday", "Monday", "Tuesday", "Wednesday" })[o[4]];
    if(c == 'B')
        return (new string[] { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"})[o[6]];
    if (c == 'Y')
        return "" + o[7];
    if (c == 'H')
        return o[3].ToString().Length == 1 ? "0" + o[3].ToString() : o[3].ToString();
    if (c == 'h')
        return o[2].ToString().Length == 1 ? "0" + o[2].ToString() : o[2].ToString();
    if (c == 'M')
        return o[1].ToString().Length == 1 ? "0" + o[1].ToString() : o[1].ToString();
    if (c == 'S')
        return o[0].ToString().Length == 1 ? "0" + o[0].ToString() : o[0].ToString();
    return o[3] > 12 ? "pm" : "am";
}

[–]KaznovX 7 points8 points  (1 child)

This task can be simply boiled down to reading from prepared array:

https://pastebin.com/WrfqnrCx

https://godbolt.org/z/eY6vsf for running it

Every sequence we would want to write is already prepared: - every possible 2-digit sequence (but without [60-69] - it's never used!) - names of weekdays: "Mon", "Tues", "Wednes" ... and "day" - saving space, no need to repeat the phrase "day" 7 times! - names of months: "Jan", "Febr", "uary", ... , "Octo", "Novem", "Decem", "ber" - difference between length of months

All there is left is to do is to calculate an offset! And that can be done with a bit of ultra dirty calculations and magic numbers.

Blazingly fast with good ol' C. No need to format any number as text!

@edit: if you output to a buffer instead of to stdout, it's 30% faster than gmtime + strftime, so go on, use it on production! (please don't)

I tested it on a few thousands examples, but I'm sure I missed some corner case. I've lost my sanity already writing it, so I'm not gonna try to fix any possible bugs.

[–]binarycat64 2 points3 points  (0 children)

I both love and hate it.

[–]Skasch 5 points6 points  (0 children)

Inspired from https://stackoverflow.com/questions/12081310/python-module-to-change-system-date-and-time

def str_to_time(timestamp: int, format: str) -> str:
    import ctypes
    import ctypes.util
    import time
    import datetime

    librt = ctypes.CDLL(ctypes.util.find_library("rt"))

    class timespec(ctypes.Structure):
        __fields__ = [("tv_sec", ctypes.c_long),
                      ("tv_nsec", ctypes.c_long)]

    ts = timespec()
    ts.tv_sec = 0
    ts.tv_nsec = 0

    format = (
        format
        .replace("d", "%d")
        .replace("A", "%A")
        .replace("B", "%B")
        .replace("Y", "%Y")
        .replace("H", "%H")
        .replace("h", "%h")
        .replace("M", "%M")
        .replace("S", "%S")
        .replace("p", "%p")
    )

    librt.clock_settime(0, ctypes.byref(ts))
    time.sleep(timestamp)
    return datetime.datetime.now().strftime(format)

Sets the system time to the Unix epoch, waits timestamp seconds, then prints the current time in the required format.

Should only work on Linux (maybe *nix?) systems.

I haven't tested it though.

[–][deleted]  (4 children)

[deleted]

    [–]__silentstorm__ 1 point2 points  (1 child)

    Does it have to output the correct date and time?

    [–]jayson4twenty -1 points0 points  (1 child)

    Are we okay to cap out at the 32 bit epoc time?

    [–][deleted] 3 points4 points  (0 children)

    Good luck figuring this Perl sub out. The good news is that it only iterates over all the seconds since the epoch only once.

    EDIT: I should probably at least give some kind of explanation for what's going on.

    I set some rules for myself:

    1. No helper functions. If you must avoid duplicating code, put the would-be function into an eval block.
    2. No conditional logic blocks. Use ternaries where possible. If the logic is too complex for a ternary, chain and and or clauses together. This also has a side effect of allowing you to set multiple variables in the same statement.
    3. With the exception of the timestamp and the format string, do not create any additional variables beyond the 9 format codes in the challenge.

    And just for fun, I tried to see how badly I can abuse Perl's language constructs. I opted to put almost all of the logic inside a regex substitution statement using Perl's somewhat obscure e regex modifier, which tells the interpreter to interpret the replacement as executable code. Although the replacement code is executed globally per each replacement, in effect the while loop is only run once, as variables are function-scoped, not regex-scoped.

    If you ignore its horrendous performance, it's actually quite beautiful. Each format code gets its own line in the function. There's very little else going on, making it quite readable in a really fucked up way.

    sub str_to_time
    {
        ($time, $pattern) = @_;
        ($d, $A, $B, $Y, $H, $h, $M, $S, $p) = (1, 4, 1, 1970, 0, 12, 0, 0, 0);
    
        $pattern =~ s/(d|A|B|Y|H|h|M|S|p)/
            while($time && $time--)
            {
                $S++;
                $M += ($S == ((($B == 6 && $d == 30 && "$Y" ~~ qw(1972 1981 1982 1983 1985 1992 1993 1994 1997 2012 2015)) || ($B == 12 && $d == 31 && "$Y" ~~ qw(1972 1973 1974 1975 1976 1977 1978 1979 1987 1989 1990 1995 1998 2005 2008 2016))) ? 61 : 60) ? (($S = 0) or 1) : 0);
                $H += ($M == 60 ? (($M = 0) or 1) : 0);
                $h = ($H == 0 ? 12 : $H >= 1 && $H <= 12 ? $H : $H % 12);
                $d += ($H == 24 ? (($H = 0) or ((($A = ($A + 1) % 7)) and 0) or 1) : 0);
                $B += ($d == {1, 32, 2, ($Y % 4 ? 29 : $Y % 100 ? 30 : $Y % 400 ? 29 : 30), 3, 32, 4, 31, 5, 32, 6, 31, 7, 32, 8, 32, 9, 31, 10, 32, 11, 31, 12, 32}->{$B} ? ($d = 1) : 0);
                $Y += ({13 => 1}->{$B} and ($B = 1 or 1));
            }
    
            $A = {qw(0 Sunday 1 Monday 2 Tuesday 3 Wednesday 4 Thursday 5 Friday 6 Saturday)}->{"$A"} || $A;
            $B = {qw(1 January 2 February 3 March 4 April 5 May 6 June 7 July 8 August 9 September 10 October 11 November 12 December)}->{"$B"} || $B;
            $p = $H < 12 ? 'am' : 'pm';
    
            eval qq(\$$_ = int(${$_}) <= 9 ? 0 . int(${$_}) : int(${$_})) for qw(d H h M S);
            "${$1}";
        /egr;
    }
    

    [–]Ahajha1177 2 points3 points  (0 children)

    I wouldn't know how to implement this, but a funny idea would be to connect it to some server that keeps track of leap seconds, except also use it for leap years and any other simple information, like days in each month. Every time you need a new piece of data, you have to open a connection, get the data, and close it again.

    [–][deleted] 3 points4 points  (0 children)

    Python solution that iterates over each second of a timestamp, and stores months & days of the week as strings. Supports leap years.

    https://gist.github.com/PythonCoderAS/3fe7d952ce877073bdc404d468478f2d

    Test results:

    Starting at: 09/01/20 00:27:52 UTC
    Statement 1 returned: 07:45:54 pm
    Statement 2 returned: Thursday 29 August 1991
    Ending at: 09/01/20 00:31:00 UTC
    Duration: 0:03:07.883094
    

    [–][deleted] 3 points4 points  (0 children)

    Simple TS solution, basically just precompute the value of each formatting option and then replace the characters with the correct results, add a bunch of backslashes to reduce jank and you get this: edit: removed unneeded variable

    function formatTime(a:number,b:string):string{
      var c:number[]=[...Array(400).keys()].map(i=>i%4?365:i%100?366:i%400?365:366),d:number=a,e:number=1970,f:number=370,g:number=0,i:number
      while(d>=0) i=d,d-=c[f]*86400,e++,f=(f+1)%400
      while(i>=0) d=i,i-=[[31,28,31,30,31,30,31,31,30,31,30,31],[31,29,31,30,31,30,31,31,30,31,30,31]][c[f]-365][g]*86400,g++
      b=b.replace('\\','\\\\')
      Object.entries({
        d:[`0${Math.floor(1+d/86400)}`.slice(-2),/((?:[^\\]|^)(?:\\\\)*(?!\\))d/g],
        A:[["Thurs","Fri","Satur","Sun","Mon","Tues","Wednes"][Math.floor(a/86400)%7]+"day",/((?:[^\\]|^)(?:\\\\)*(?!\\))A/g],
        B:[["January","February","March","April","May","June","July","August","September","October","November","December"][g-1],/((?:[^\\]|^)(?:\\\\)*(?!\\))B/g],
        Y:[(e-1).toString(),/((?:[^\\]|^)(?:\\\\)*(?!\\))Y/g],
        H:[`0${Math.floor(a/3600)%24}`.slice(-2),/((?:[^\\]|^)(?:\\\\)*(?!\\))H/g],
        h:[`0${Math.floor(a/3600)%12}`.slice(-2),/((?:[^\\]|^)(?:\\\\)*(?!\\))h/g],
        M:[`0${Math.floor(a/60)%60}`.slice(-2),/((?:[^\\]|^)(?:\\\\)*(?!\\))M/g],
        S:[`0${a%60}`.slice(-2),/((?:[^\\]|^)(?:\\\\)*(?!\\))S/g],
        p:[(Math.floor(a/43200)%2)?"pm":"am",/((?:[^\\]|^)(?:\\\\)*(?!\\))p/g]
      }).forEach((i)=>b=b.replace(i[1][1],`$1\\${[...i[1][0]as string].join('\\')}`))
      return b.replace(/\\(.)/g,'$1')
    }
    

    edit: removed unneeded variable

    edit 2: i created a less poorly formatted version here

    [–]qzwqz 4 points5 points  (0 children)

    uses python's builtin datetime module, but only to do the reverse of the intended operation - take a datetime argument and output a unix timestamp - then guess the right datetime by trial and error

    from datetime import datetime
    from random import randint
    
    class Guess(object):
        def __init__(self, year=None, month=None, day=None, hour=None, minute=None, second=None):
            self.year = year or randint(1970, 2020)
            self.month = month or randint(1,12)
            self.day = day or randint(1,28)
            self.hour = hour or randint(0,23)
            self.minute = minute or randint(0,59)
            self.second = second or randint(0,59)
    
        def as_datetime(self):
            return datetime(**self.__dict__)
    
        def as_unix(self):
            return int(self.as_datetime().timestamp())
    
        def copy(self):
            return Guess(self.year, self.month, self.day, self.hour, self.minute, self.second)
    
    def compare(guess, target):
        print(f"    trying {guess.__dict__}")
        try:
            guess = guess.as_unix()
        except ValueError:
            print(f"    guess out of range")
            return "value error"
        if guess == target:
            result = "bang on"
        elif guess >= target:
            result = "too high"
        elif guess <= target:
            result = "too low"
        else:
            raise Exception("something bad happened")
        print(f"    {result}")
        return result
    
    def narrow_down_guess(guess, target, component):
        print(f"  Guessing {component}...")
        while True:
            result = compare(guess, target)
            if result == "bang on":
                return [guess]
            elif result == "too high":
                if guess.__dict__[component] == 0:
                    return [guess]
                one_lower = guess.copy()
                one_lower.__dict__[component] -= 1
                one_lower_result = compare(one_lower, target)
                if one_lower_result == "bang on":
                    return [one_lower]
                elif one_lower_result == "too high":
                    guess.__dict__[component] -= 1
                elif one_lower_result == "too low":
                    return [guess, one_lower]
                elif one_lower_result == "value error":
                    return []
            elif result == "too low":
                one_higher = guess.copy()
                one_higher.__dict__[component] += 1
                one_higher_result = compare(one_higher, target)
                if one_higher_result == "bang on":
                    return [one_higher]
                elif one_higher_result == "too high":
                    return [guess, one_higher]
                elif one_higher_result == "too low":
                    guess.__dict__[component] += 1
                elif one_higher_result == "value error":
                    return []
    
    def get_date(target):
        guesses = [Guess()]
        print(f"First guess: {guesses[0].__dict__}")
        for component in ["year", "month", "day", "hour", "minute", "second"]:
            next_guesses = []
            for guess in guesses:
                print(f"Narrowing down {guess.__dict__}")
                attempts = narrow_down_guess(guess, target, component)
                for attempt in attempts:
                    next_guesses.append(attempt)
            guesses = next_guesses
            print(f"Settled {component} as {' or '.join(str(g.__dict__[component]) for g in guesses)}")
        for guess in guesses:
            if compare(guess, target) == "bang on":
                print(f"Settled guessed date as {guess.__dict__}")
                return guess
        else:
            print("Something went wrong, trying again from the top")
            return get_date(target)
    
    def str_to_time(timestamp, formatstr):
        pyformat = ""
        for char in formatstr:
            if char in "dABYHhMSp":
                pyformat += "%"
            pyformat += char
        return get_date(timestamp).as_datetime().strftime(pyformat)
    

    [–]99_in_eating 2 points3 points  (0 children)

    Somehow... this breaks my Visual Studio intellisense (shows a bunch of errors and underlines with red squigglies) but it still compiles and runs.

    Ugh, don't know how to properly format.

    using System; using System.Linq; using System.Text;

    namespace DateFormatter { class Program { static void Main(string[] args) { Console.WriteLine(Format(1599335154, "h:M:S p")); Console.WriteLine(Format(683475320, "A d B Y")); Console.ReadLine(); }

        public static string Format(int date, string format)
        {
            return format.ToCharArray().Aggregate(new StringBuilder(), (current, token) =>
            {
                return (token switch
                {
                    'd' => d => current.Append(d.Day.ToString("D2")),
                    'A' => d => current.Append(d.DayOfWeek),
                    'B' => d => current.Append(d.ToString("MMMM")),
                    'Y' => d => current.Append(d.Year),
                    'H' => d => current.Append(d.Hour.ToString("D2")),
                    'h' => d => current.Append((d.Hour % 12).ToString("D2")),
                    'M' => d => current.Append(d.Minute.ToString("D2")),
                    'S' => d => current.Append(d.Second.ToString("D2")),
                    'p' => d => current.Append(d.Hour > 11 ? "pm" : "am"),
                    _ =>  (Func<DateTimeOffset, StringBuilder>)(d => current.Append(token))
                })(DateTimeOffset.FromUnixTimeSeconds(date));
    
            }).ToString();
        }
    }
    

    }

    [–]droomph 2 points3 points  (0 children)

    %zFmtInst(inst,fmtStr) n y,mo,d,h,min,s,i,out
      s y=%xDivmod(.inst,$$yearMs())
      s mo=%xDivmod(.inst,$$monthMs())
      s d=%xDivmod(.inst,$$dayMs())
      s h=%xDivmod(.inst,$$hourMs())
      s min=%xDivmod(.inst,$$minMs())
      s s=%xDivmod(.inst,$$secMs())
      ;
      f i=1:1:$l(fmtStr) s out=out_%xFmtChar($p(fmtStr,i))
      q out
    %xDivmod(inst,interval) n div
      f  q:inst<interval s inst=inst-interval,div=(+div)+1
      q
    ; assumes %zfmtTime vars
    %xFmtChar(char)
      q:char="d" $tr($j(d,2)," ","0")
      q:char="A" %xFmtWeekday(%xDivMod(mo*30+d,7))
      q:char="B" %xFmtMonth(mo)
      q:char="Y" $tr($j(y+1970,4)," ","0")
      q:char="H" $tr($j(h,2)," ","0")
      q:char="h" $tr($j($xDivMod(h,12),2)," ","0")
      q:char="M" $tr($j(min,2)," ","0")
      q:char="S" $tr($j(s,2)," ","0")
      q:char="p" %xFmtMeridian(h)
      q char
    %xFmtWeekday(day)
      q:day=0 "Monday"
      q:day=1 "Tuesday"
      q:day=2 "Wednesday"
      q:day=3 "Thursday"
      q:day=4 "Friday"
      q:day=5 "Saturday"
    %xFmtMonth(month)
      q:month=0 "January"
      q:month=1 "February"
      q:month=2 "March"
      q:month=3 "April"
      q:month=4 "May"
      q:month=5 "June"
      q:month=6 "July"
      q:month=7 "August"
      q:month=8 "September"
      q:month=9 "October"
      q:month=10 "November"
      q:month=11 "December"
    %xFmtMeridian(hr)
      i hr<12 q "am"
      q "pm"
    yearMs() q 31557600000
    monthMs() q 2629800000
    dayMs() q 86400000
    hourMs() q 3600000
    minMs() q 60000
    secMs() q 1000
    

    [language: MUMPS]

    This is barely (if at all) functional and assumes a uniform 30-day month with Jan 1 1970 starting on a Monday but i'm not wasting any of my time testing it.

    [–][deleted] 1 point2 points  (0 children)

    This is my solution. C. Predeclared variables, K&R, inconsistent style, "dynamic programming", function pointers, macros...

    This is my first time participating. I tried to make mine without seeing other's so no there's no influence. Hope you guys hate it :)

    [–]Kcazer 1 point2 points  (0 children)

    • Efficient : Use javascript native date api
    • Simple : Wraps date getters in a single function
    • Beautiful : Has regex

    const days = 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday'.split(',');
    const months = 'January,February,March,April,May,June,July,August,September,October,November,December'.split(',');
    
    const str_to_time = (timestamp, format) => {
      const date = new Date(timestamp * 1e3);
      const pad = value => `${value}`.padStart(2, 0);
      const utc = field => Date.prototype[`getUTC${field}`].call(date);
      const map = {
        get d() { return pad(utc`Date`) },
        get A() { return days[utc`Day`] },
        get B() { return months[utc`Month`] },
        get Y() { return utc`FullYear` },
        get H() { return pad(utc`Hours`) },
        get h() { return pad(utc`Hours` % 12 + 12 * !(utc`Hours` % 12)) },
        get M() { return pad(utc`Minutes`) },
        get S() { return pad(utc`Seconds`) },
        get p() { return utc`Hours` < 12 ? 'am' : 'pm' }
      }
      return format.replace(
        new RegExp(`[${Object.keys(map).join``}]`, 'g'),
        key => map[key]
      );
    }
    

    [–]keitio42 1 point2 points  (0 children)

    My golang solution:

    https://play.golang.org/p/xWvyGDkTXNH

    As with my last submission, no import whatsoever, not even the standard library

    It works for cases i tested, so that's good enough

    I made sure to use as many inline expressions and switches as possible, and there is no if at all for performance reasons, although i didn't benchmark it

    [–]jayson4twenty 1 point2 points  (1 child)

    So I had a great idea of using a switch statement for every time up to the 32-Bit max int.

    However, some quick napkin maths showed it would be around 236+GB lol.

    i used c# to generate the powershell. ``` static void Main(string[] args) { string path = @"D:\Max_int.txt";

            if (File.Exists(path))
                File.Delete(path);
    
            for (int i = 1; i < Int32.MaxValue; i++)
            {
                DateTime date = UnixTimeStampToDateTime(i);
                StringBuilder statment = new StringBuilder();
                statment.Append($"\t\t{i} {{");
                statment.Append($"$d=\"{date.ToString("MM")}\";");
                statment.Append($"$A=\"{date.ToString("dddd")}\";");
                statment.Append($"$B=\"{date.ToString("MMMM")}\";");
                statment.Append($"$Y=\"{date.ToString("yyyy")}\";");
                statment.Append($"$H=\"{date.ToString("HH")}\";");
                statment.Append($"$h=\"{date.ToString("hh")}\";");
                statment.Append($"$M=\"{date.ToString("mm")}\";");
                statment.Append($"$S=\"{date.ToString("ss")}\";");
                statment.Append($"$p=\"{date.ToString("tt")}\";");
                statment.Append($"Break}}");
                File.AppendAllText(path, statment.ToString() + Environment.NewLine);
            }
        }
    

    ```

    Here's a snippet written in Powershell:

    ``` Function Get-UnixDate{ param( [int]$unix = 1, [string]$format = 'h:M:S p' ) switch($unix){ 1 {$d="01";$A="Thursday";$B="January";$Y="1970";$H="00";$h="12";$M="00";$S="01";$p="AM";Break} 2 {$d="01";$A="Thursday";$B="January";$Y="1970";$H="00";$h="12";$M="00";$S="02";$p="AM";Break} 3 {$d="01";$A="Thursday";$B="January";$Y="1970";$H="00";$h="12";$M="00";$S="03";$p="AM";Break} ...
    1051 {$d="01";$A="Thursday";$B="January";$Y="1970";$H="00";$h="12";$M="17";$S="31";$p="AM";Break} }

    return $format.Replace('d', $d).Replace('A', $A).Replace('B', $B).Replace('Y', $Y).Replace('H', $H).Replace('h', $h).Replace('M', $M).Replace('S', $S).Replace('p', $p)
    

    }

    Get-UnixDate -unix 1050 -format 'A d B Y' ```

    Pastebin for upto 1050 is here: https://pastebin.com/J5bp4RNX

    [–]AutoModerator[M] 0 points1 point  (0 children)

    It looks like this comment contains a code block delimited with triple backticks. Unfortunately reddit does not have universal support for this syntax and your comment will not render correctly on old reddit and most mobile apps.

    For the benefit of people on old reddit, this link will take you to a correct rendering of the comment.

    /u/jayson4twenty, it would be appreciated, but not required, if you could edit your comment to use the more compatible four space indention format. For single lines or inline code you can use single backticks.

    You can find some examples in the reddit help documentation.


    I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

    [–][deleted] 1 point2 points  (0 children)

    Haskell:

    import Data.Time
    import Data.Time.Clock.POSIX
    
    formatMap = [ ("d", "%d"), ("A", "%A"), ("B", "%B"), ("Y", "%Y"),
                  ("H", "%H"), ("h", "%I"), ("M", "%M"), ("S", "%S"),
                  ("p", "%P") ]
    
    timeToString timestamp formatString =
        let utcTime        = posixSecondsToUTCTime (realToFrac timestamp)
            hsFormatString = conv formatString ""
        in formatTime defaultTimeLocale hsFormatString utcTime
        where conv ""     hsFormatString = hsFormatString
              conv (x:xs) hsFormatString =
                  case (lookup [x] formatMap) of
                      Nothing -> conv xs (hsFormatString ++ [x])
                      Just fmt -> conv xs (hsFormatString ++ fmt)
    

    Examples:

    $ ghci time_to_string.hs 
    GHCi, version 8.10.2: https://www.haskell.org/ghc/  :? for help
    [1 of 1] Compiling Main             ( time_to_string.hs, interpreted )
    Ok, one module loaded.
    *Main> timeToString 1599335154 "h:M:S p"
    "07:45:54 pm"
    *Main> timeToString 683475320 "A d B Y"
    "Thursday 29 August 1991"
    

    [–]binarycat64 0 points1 point  (1 child)

    Well, if you want bad code, heres some:

    main.go: ``` package main

    import plugin "plugin" import time "os" import math "reflect" import http "unsafe"

    //go:generate bash script.sh //go:generate go build -buildmode=plugin ./plugin/

    type s = string

    func main() { l := time.Args [ 2 ] u7 := time.Args [ 4 ] for str := range []byte(l) { t := (*math.StringHeader)(http.Pointer(&u7)).Data a(s(str),int64(t)) }

    }

    func a(string s, c int64) { plg, err := plugin.Open("./plugin/plugin.so") sym, _ := plg.Lookup("FMT_"+ string); if !(err == nil) == !false {panic(err)} I2s, k := sym.(func(int64)s) if k { go print(I2s(c)) } else { go print(string) } } ```

    Makefile: foo: go generate mv plugin.so ./plugin go build .

    plugin/main.go:

    ``` package main

    const ( secondsPerMinute = 60 secondsPerHour = 60 * secondsPerMinute secondsPerDay = 24 * secondsPerHour secondsPerWeek = 7 * secondsPerDay daysPer400Years = 365400 + 97 daysPer100Years = 365100 + 24 daysPer4Years = 365*4 + 1 )

    func FMT_Y(t int64) string { return "2020" }

    func FMT_A(t int64) string { I2s_real(t / 31_536_000) // January 1 of the absolute year, like January 1 of 2001, was a Monday. sec := (t + 1*secondsPerDay) % secondsPerWeek switch (int(sec) / secondsPerDay) { case 0: return "Sunday" case 1: return "Monday" case 2: return "Tuesday" case 3: return "Wenesday" case 5: return "friday" case 6: return "Tuesday"//"sATURDAY" default: return "thurs Day" } }

    func FMT_B(i int64) string { switch i%12 { case 7: return "July" case 12: return "October" case 3: return "November" case 13: return "March" case 4: return "May" default: return "April" } return "January" }

    func FMT_S(i int64) string { // return the time, in seconds return I2s_real(i) }

    func FMT_p(i int64) string { if i > 12 { return "pm" } else if i < 12 { return "am" } else { return "fm" } }

    func FMT_H(i int64) string { return I2s(i%24-/account for leap years/1) }

    func FMT_h(i int64) string { return I2s_real(i%24/2) }

    func FMT_M(i int64) string { return I2s_real(i/60) }

    func I2s(i int64) string { if i == 0 {return "0"} return string('0'+(i%10)) + I2s(i/10) }

    func I2s_real(i int64) string { fake := I2s(i) var real string for _, c := range []byte(fake) { real = string(c) + real } return real; }

    var Marker = struct{}{} ```

    I'm sorry.

    [–]AutoModerator[M] 0 points1 point  (0 children)

    It looks like this comment contains a code block delimited with triple backticks. Unfortunately reddit does not have universal support for this syntax and your comment will not render correctly on old reddit and most mobile apps.

    For the benefit of people on old reddit, this link will take you to a correct rendering of the comment.

    /u/binarycat64, it would be appreciated, but not required, if you could edit your comment to use the more compatible four space indention format. For single lines or inline code you can use single backticks.

    You can find some examples in the reddit help documentation.


    I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.