69
\$\begingroup\$

Basing on this SO question.

Challenge is rather simple: given a date period in the format YYYYMM output it in the format MMMYY.

Rules:

  • The input will be a number or a string exactly 6 characters long, consisting only of digits.
  • Last two digits will be between 01 and 12.
  • Output must be in the form MMMYY, where MMM represents uppercase three-letter code for the month (below) and YY represents two last digits of the YYYY part of the input.

List of months with corresponding code:

MM    MMM
01    JAN
02    FEB
03    MAR
04    APR
05    MAY
06    JUN
07    JUL
08    AUG
09    SEP
10    OCT
11    NOV
12    DEC

Examples:

Input     Output
201604    APR16
200001    JAN00
000112    DEC01
123405    MAY34
\$\endgroup\$
2
  • 6
    \$\begingroup\$ This question is very well-balanced. Both manual parsing and date libraries end up being about the same, at least in Python. \$\endgroup\$
    – jqkul
    Commented Jun 22, 2016 at 20:32
  • 13
    \$\begingroup\$ Yesterday, I saw "Convert YYYYMM to MMMYY" on HNQ beside the SO logo. Now I see the same title beside the PCG logo. I was very confused :) \$\endgroup\$
    – cat
    Commented Jun 23, 2016 at 14:30

70 Answers 70

26
\$\begingroup\$

Python 3, 70 bytes

from time import*
lambda s:strftime("%b%y",strptime(s,"%Y%m")).upper()

This uses the built-in strftime and strptime functions.

For 1 byte more, here's a version which parses the string manually:

lambda s:" JFMAMJJASONDAEAPAUUUECOENBRRYNLGPTVC"[int(s[4:])::12]+s[2:4]

This encodes the month names in an interesting way (thanks to Henry Gomersall for saving a byte).

\$\endgroup\$
9
  • 14
    \$\begingroup\$ That manual parsing is crazy. \$\endgroup\$ Commented Jun 22, 2016 at 20:59
  • \$\begingroup\$ @MorganThrapp I got the idea from this answer. \$\endgroup\$
    – jqkul
    Commented Jun 22, 2016 at 21:09
  • 1
    \$\begingroup\$ Your manual version can be done in 69 bytes in Python 2 if you take a number as input: lambda n:"JFMAMJJASONDAEAPAUUUECOENBRRYNLGPTVC"[n%100-1::12]+`n`[2:4]. \$\endgroup\$
    – xnor
    Commented Jun 23, 2016 at 8:39
  • 1
    \$\begingroup\$ Though this loses a byte: lambda s:" JFMAMJJASONDAEAPAUUUECOENBRRYNLGPTVC"[int(s[4:])::12]+s[2:4] \$\endgroup\$ Commented Jun 23, 2016 at 10:03
  • 1
    \$\begingroup\$ @a25bedc5-3d09-41b8-82fb-ea6c353d75ae - "import time" would save you 6 characters, but would cost you 10 ("time.", twice) \$\endgroup\$
    – TLW
    Commented Jun 24, 2016 at 3:10
20
\$\begingroup\$

MATL, 18 14 13 bytes

4e!Z{Zc12XOXk

Input is provided as a string (enclosed in single quotes).

This version only runs in MATL on MATLAB since MATLAB is able to automatically parse datestr('2016 04').

Explanation

        % Implicitly grab input as a string
4e!     % Reshape input to be 2 x 4 (puts the year in row 1 and month in row 2)
Z{      % Place each row in a separate cell
Zc      % Join them together using a space to create 'yyyy mm' format
12      % Number literal, pre-defined datestring of 'mmmyy'
XO      % Convert from serial date number to string using this format
Xk      % Convert to uppercase
        % Implicitly display
    

Here is an 18 byte version which works on Octave (and therefore the online interpreter)

'yyyymm'2$YO12XOXk

Try it Online

Modified version for all test cases

Explanation

            % Implicitly grab input as a string
'yyyymm'    % Push the format string as a string literal
2$YO        % Convert to a serial date number
12          % Number literal, pre-defined datestring of 'mmmyy'
XO          % Convert from serial date number to string using this format
Xk          % Convert to uppercase
            % Implicitly display
\$\endgroup\$
1
  • 3
    \$\begingroup\$ I don't see how this can be beaten so.. gg \$\endgroup\$
    – Adnan
    Commented Jun 22, 2016 at 21:01
19
\$\begingroup\$

Bash + coreutils, 18

Requires 64-bit version of date for the given testcases, which recognises dates earlier than 14th December 1901.

date -d$101 +%^b%y
\$\endgroup\$
19
\$\begingroup\$

PowerShell, 49 46 40 bytes

date "$args".insert(4,'-')-U %b%y|% *per

Try it online!

Thanks to @Joey for saving 3 bytes!

Takes input $args as an explicit string (e.g., '201604') via command-line input. Uses the string.Insert() function to put a - in the appropriate space, and that resultant string forms input to the Get-Date cmdlet with the -Uformat parameter specifying the three-month shorthand plus two-digit year. We then tack on a .ToUpper() to make the output string capitalized. That string is left on the pipeline and printing is implicit.

Also, as pointed out, this is locale-sensitive. Here's the locale information that I'm using where this works correctly.

PS C:\Tools\Scripts\golfing> get-culture

LCID             Name             DisplayName
----             ----             -----------
1033             en-US            English (United States)
\$\endgroup\$
2
  • 1
    \$\begingroup\$ You don't need to quote the MMMyy, since it's a simple argument to a cmdlet. You also could just use -UFormat %b%y, i.e. -u %b%y instead, which is even shorter. Side note: This solution is locale-sensitive (which I personally dislike), but would be a fair bit longer to account for that, admittedly. \$\endgroup\$
    – Joey
    Commented Jun 24, 2016 at 15:00
  • \$\begingroup\$ Excellent call with the -UFormat instead. Thanks! I also did not know about the quotes around MMMyy - that's good to know for the future. \$\endgroup\$ Commented Jun 24, 2016 at 15:19
10
\$\begingroup\$

Retina, 71 70 bytes

Thanks to Sp3000 for saving 1 byte.

Byte count assumes ISO 8859-1 encoding. The trailing linefeed is significant.

(..)(..)$
DECNOVOCTSEPAUGJULJUNMAYAPRMARFEBJANXXX$2$*¶$1
+`...¶

R-6`.

Try it online!

Explanation

Taking 201604 as an example:

(..)(..)$
DECNOVOCTSEPAUGJULJUNMAYAPRMARFEBJANXXX$2$*¶$1

This swaps the last two digits of the year with the month while also expanding the month in unary using linefeeds, and prepending the list of months in reverse so we'd get:

20DECNOVOCTSEPAUGJULJUNMAYAPRMARFEBJANXXX¶¶¶¶16

Where the represent linefeeds (0x0A).

+`...¶

Now we repeatedly remove three non-linefeed characters followed by a linefeed. That is we eat up the list of months from the end for each linefeed representing a month:

20DECNOVOCTSEPAUGJULJUNMAYAPRMARFEBJANXXX¶¶¶¶16
20DECNOVOCTSEPAUGJULJUNMAYAPRMARFEBJAN¶¶¶16
20DECNOVOCTSEPAUGJULJUNMAYAPRMARFEB¶¶16
20DECNOVOCTSEPAUGJULJUNMAYAPRMAR¶16
20DECNOVOCTSEPAUGJULJUNMAYAPR16

This is why we've inserted that XXX: since the months start counting from 1, we'll always remove at least three characters, even for January.

R-6`.

Finally, we remove everything up to the 6th character from the end. In other words we only keep the last five characters.

\$\endgroup\$
1
  • \$\begingroup\$ That's pretty dang clever. \$\endgroup\$ Commented Jun 24, 2016 at 12:35
7
\$\begingroup\$

CJam, 50 46 bytes

q2/1>~i("4H~0ë~³!ò²×¶7Ö"256b25b'Af+3/=\

Try it online. Thanks to Martin Ender for compressing the string to save a few bytes.

Explanation

q2/  e# Get input and divide it into groups of 2, like ["20" "16" "04"]
1>~  e# Discard the first item and dump the remaining array to the stack
i(   e# Convert the top value (month) to an integer and decrement it, because
     e# arrays are zero-indexed
"..."256b25b e# Convert this string from base-256 to base-25
'Af+ e# "Add" a capital A to each number to get the letters
3/   e# Divide into groups of 3 to make an array of month names
=\   e# Get the requested month and swap the elements to put the year on
     e# top, so it is printed last
\$\endgroup\$
0
7
\$\begingroup\$

Bash, 39 28 bytes

date -d$101 +%b%y|tr a-z A-Z

Thanks Digital Trauma!

\$\endgroup\$
0
6
\$\begingroup\$

MATLAB / Octave, 42 bytes

@(x)upper(datestr(datenum(x,'yyyymm'),12))

Creates an anonymous function named ans that is called with a string representing the date: ans('201604').

Online Demo

This solution uses datenum to convert the input date to a serial date number, and then datestr with the predefined output spec of mmmyy (12) to yield the string representation in the required format. Finally, we use upper to change it to MMMYY since the uppercase month is not an output option.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Wow, gj on beating everyone else in a non-golfing language! \$\endgroup\$
    – Downgoat
    Commented Jun 22, 2016 at 20:44
6
\$\begingroup\$

Java 7, 137 characters (161 bytes)

String d(String i){return Integer.toString("憯䷳烣㘿烪摿摽㛨近筍矯䏔".charAt(Integer.parseInt(i.substring(4))-1),36).toUpperCase()+i.substring(2,4);}

Consider each month name (JAN, FEB etc...) is a number in base 36 and encode it into corresponding Unicode symbol. Then get corresponding symbol from the string encode it back again in base 36 and after that some plain string manipulations.

Slightly ungolfed:

String d(String input){
return 
  Integer.toString("憯䷳烣㘿烪摿摽㛨近筍矯䏔" // encoded month names
  .charAt(Integer.parseInt(input.substring(4))-1),36) // get a symbol from encoded names at position input[4:], decode it to base 36 value
  .toUpperCase()+input.substring(2,4); // get it to upper case and add year
}

You can see it running here: https://ideone.com/IKlnPY

\$\endgroup\$
5
\$\begingroup\$

Python, 83 bytes

from datetime import*
lambda x:datetime.strptime(x,'%Y%m').strftime('%b%y').upper()
\$\endgroup\$
2
  • \$\begingroup\$ I just posted an answer nearly identical to yours. I didn't see yours because it took a while to write the answer. If you want me to delete mine, I will, or you can use mine to get some extra bytes off. \$\endgroup\$
    – jqkul
    Commented Jun 22, 2016 at 20:32
  • 1
    \$\begingroup\$ That's fine, you beat me by 13 bytes, I'll concede. I like your manual answer, too. \$\endgroup\$ Commented Jun 22, 2016 at 20:45
5
\$\begingroup\$

Kotlin, 100 bytes

fun f(d:String)=SimpleDateFormat("MMMyy").format(SimpleDateFormat("yyyyMM").parse(d)).toUpperCase()

Pretty straight forward use of Java SimpleDateFormat

\$\endgroup\$
2
  • 1
    \$\begingroup\$ Hmm, I don't know Kotlin, but since it's derived from Java, shouldn't you include the import of the SimpleDateFormat (i.e. import java.text.*;)? \$\endgroup\$ Commented Jun 23, 2016 at 7:10
  • \$\begingroup\$ Since the challenge asks for output, I would assume a print is required as part of your function. \$\endgroup\$
    – JohnWells
    Commented Apr 6, 2018 at 21:48
5
\$\begingroup\$

05AB1E, 51 42 41 bytes

2ô¦`ï<•r–ºþ¯Bê€õaPù£—^5AºüLwÇ–è•35B3ôsèsJ

Explanation

                                           # implicit input, 123405
2ô                                         # split input into pieces of 2, ['12','34','05']
  ¦`                                       # push last 2 elements to stack, '05', '34'
    ï<                                     # convert month to its int index, 4
      •r–ºþ¯Bê€õaPù£—^5AºüLwÇ–è•35B        # get compressed string containing 3-letter months, 
                                             JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC
                                   3ô      # split into pieces of 3
                                             ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC']
                                     sè    # get month at index retrieved earlier, MAY
                                       sJ  # join with 2-digit year and implicitly print, MAY34

Try it online

9 bytes saved thanks to string compression, courtesy of @Adnan

\$\endgroup\$
1
  • 1
    \$\begingroup\$ •r–ºþ¯Bê€õaPù£—^5AºüLwÇ–è•35B instead of "JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC" saves 9 bytes. \$\endgroup\$
    – Adnan
    Commented Jun 22, 2016 at 20:23
5
\$\begingroup\$

JavaScript, 87 84 80 79 bytes

x=>(new Date(x.replace(/.{4}/,'$&-'))+'').slice(4,7).toUpperCase()+x.slice(2,4)

To get the month, gets the date (which is formed of "YYYYMM" converted to "YYYY-MM") and retrieves the characters 5 to 8, that are exactly the first three letters of the month. But it costs much to convert it to upper case.

Demo:

function s(x) {
  return (new Date(x.replace(/.{4}/, '$&-')) + '').slice(4,7)
         .toUpperCase() + x.slice(2, 4)
}

console.log(s('201604'));
console.log(s('200001'));
console.log(s('000112'));
console.log(s('123405'));

\$\endgroup\$
15
  • \$\begingroup\$ First should be APR16 \$\endgroup\$
    – Downgoat
    Commented Jun 22, 2016 at 20:34
  • \$\begingroup\$ @Upgoat And what's appearing for you? \$\endgroup\$
    – nicael
    Commented Jun 22, 2016 at 20:35
  • 1
    \$\begingroup\$ I'm getting MAR16 \$\endgroup\$
    – Downgoat
    Commented Jun 22, 2016 at 20:40
  • \$\begingroup\$ @Upgoat Huh, that's weird, why could it be this way? Because I get this. \$\endgroup\$
    – nicael
    Commented Jun 22, 2016 at 20:41
  • \$\begingroup\$ For me it does show APR16, but the third test case shows only DEC for me. \$\endgroup\$
    – Adnan
    Commented Jun 22, 2016 at 20:42
5
\$\begingroup\$

Julia, 57 56 53 bytes

s->uppercase(Dates.format(DateTime(s,"yyyym"),"uyy"))

This is an anonymous function that accepts a string and returns a string. To call it, assign it to a variable.

First we construct a DateTime object using the type constructor and a format string. Note that the single m in the format string will get both one- and two-digit months, though the former case is irrelevant here. Since no days are specified, the first of the month is assumed.

We can then format the value as a string using the Dates.format function from the Base.Dates submodule. The string uyy gets the three-letter month name and two-digit year, but the result is in title case, e.g. Apr16 instead of the desired APR16, so we need to uppercase it.

Try it online! (includes all test cases)

\$\endgroup\$
5
\$\begingroup\$

JavaScript ES6, 77 66 bytes

Saved 11 bytes thanks to @Bálint!

a=>(new Date(0,a[4]+a[5]-1)+"").slice(4,7).toUpperCase()+a[2]+a[3]

Get's the date by extracting the string returned by the Date class. then capitalizes and adds the year.

ES5 version:

var a = prompt("Enter YYYYMM: ");
result = (new Date(0,a[4]+a[5]-1)+"").slice(4,7).toUpperCase()+a[2]+a[3]
alert(result);

\$\endgroup\$
14
  • \$\begingroup\$ I made one in 66 bytes with the same atob technique, but I can't copy it out \$\endgroup\$
    – Bálint
    Commented Jun 22, 2016 at 20:34
  • \$\begingroup\$ @Bálint I thought I got 66 bytes too but turns our byte counter was wrong due to to bad copy pasting ;) \$\endgroup\$
    – Downgoat
    Commented Jun 22, 2016 at 20:36
  • \$\begingroup\$ You could get the month's name with (Date(0,a[4]- -a[5])+"").substr(4,3) \$\endgroup\$
    – Bálint
    Commented Jun 22, 2016 at 21:09
  • 1
    \$\begingroup\$ I don't get that a[4]- -a[5]. What was wrong with a[4]+a[5]-1? \$\endgroup\$
    – Neil
    Commented Jun 22, 2016 at 22:55
  • 1
    \$\begingroup\$ new Date(0,a[4]+a[5]-1)+"" => new Date(0,a[4]+a[5]-1)+0 \$\endgroup\$
    – l4m2
    Commented Apr 7, 2018 at 0:53
4
\$\begingroup\$

C, 147 145 112 bytes

main(m){char a[99]="JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC";scanf("%4s%d",a+50,&m);printf("%.3s%s",a+--m*3,a+52);}

Online demo

Thanks ugoren!

\$\endgroup\$
4
  • 2
    \$\begingroup\$ Some cheap tricks - delete the #include, define m as a parameter - main(m), \$\endgroup\$
    – ugoren
    Commented Jun 23, 2016 at 15:07
  • 2
    \$\begingroup\$ Also, the %.3s format saves the null termination. \$\endgroup\$
    – ugoren
    Commented Jun 23, 2016 at 15:09
  • \$\begingroup\$ Thanks @ugoren! I also changed "%4s%2d" to "%4s%d". \$\endgroup\$
    – Marco
    Commented Jun 23, 2016 at 16:00
  • \$\begingroup\$ main(m){char a[9];scanf("%4s%d",a,&m);printf("%.3s%s","JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC"+--m*3,a+2);} lot shorter \$\endgroup\$
    – l4m2
    Commented Apr 8, 2018 at 13:49
3
\$\begingroup\$

C#, 94 87 bytes

string C(string s)=>System.DateTime.Parse(s.Insert(4,"-")).ToString("MMMyy").ToUpper();

Saved 7 bytes by using C#6 Syntax.

Try Online

\$\endgroup\$
1
  • \$\begingroup\$ You can leave off return type information for lambdas, i.e C(string s)=>... \$\endgroup\$
    – cat
    Commented Jun 24, 2016 at 17:58
3
\$\begingroup\$

Japt, 35 34 bytes

ÐUr$/..../$,"$&-")+P s4,7 u +Us2,4

Link.

Uses the same technique as my JavaScript answer.

\$\endgroup\$
0
3
\$\begingroup\$

Java 8, 154 113 bytes

import java.text.*;s->new SimpleDateFormat("MMMyy").format(new SimpleDateFormat("yyyyMM").parse(s)).toUpperCase()

Explanation:

Try it online.

import java.text.*;                 // Required import for SimpleDateFormat
s->                                 // Method with String as both parameter and return-type
  new SimpleDateFormat("MMMyy")     //  Create a formatter with format "MMMyy"
   .format(                         //  Format the following:
     new SimpleDateFormat("yyyyMM") //   Create another formatter with format "yyyyMM"
     .parse(s))                     //   Parse the input with this format
  .toUpperCase()                    //  Convert everything to Uppercase and return
\$\endgroup\$
4
  • \$\begingroup\$ I think you can shorten it if you remove the import and instead directly refer to it with java.text.SimpleDateFormat. \$\endgroup\$
    – Frozn
    Commented Jun 23, 2016 at 14:22
  • 2
    \$\begingroup\$ @Frozn Actually, import java.text.*; is 19 bytes, and two times java.text. in front of both SimpleDateFormat is 20 bytes. So it would increase by 1 byte instead of lowering it. \$\endgroup\$ Commented Jun 23, 2016 at 14:53
  • \$\begingroup\$ Oh yea you're right. I always look at the ungolfed version and think that it's equal to the golfed one. Sorry :) \$\endgroup\$
    – Frozn
    Commented Jun 25, 2016 at 9:50
  • \$\begingroup\$ @Frozn Ah, also a bit my bad. Usually I still use .*; for the ungolfed code, but this time I seem to have neglected it. I have save options that automatically converts it to pure imports since I use Java in my job, and I simply forgot to change it to import java.text.*;.. \$\endgroup\$ Commented Jun 25, 2016 at 10:32
3
\$\begingroup\$

Pyth, 45 bytes

+:."AYw2ûDÈëKH§È¼DYÉx\E±oË"J*3sgz5+3J:z2 4

Try it online!

Explanation:

+:."AYw2ûDÈëKH§È¼DYÉx\E±oË"J*3sgz5+3J:z2 4
                                z           Take the input
                               g 5          Slice inclusively from index 5 to the end
                              s             Parse as an int
                            *3              Multiply by 3
                           J                Store in variable J, this also returns J
 :                                          Take a slice
  ."AYw2ûDÈëKH§È¼DYÉx\E±oË"                 Of this packed string
                           J*3sgz5          From the J we defined before
                                  +3J       To J+3
+                                           To this string, append
                                     :z     A slice of the index
                                       2 4  From [2,4).

The packed string contains "JANJANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC". The two JANs are so that I can index it pseudo-one-indexed.

EDIT: Fixed bug that was messing with TIO

\$\endgroup\$
3
\$\begingroup\$

Microsoft Excel VBA, 47 Bytes

Anonymous VBE immediate window function that takes input from range [A1] and outputs to the VBE immediate window

?UCase(MonthName([Right(A1,2)],1))[Mid(A1,3,2)]

Current version thanks to @Engineer Toast, for pointing out the abbreviate option of the MonthName function.

Previous Version

?UCase(Format(DateSerial([Left(A1,4)],[Right(A1,2)],1),"MMMYY"))
\$\endgroup\$
3
  • \$\begingroup\$ Worth noting that Excel needs to be set to English, otherwise it returns locale-specific month name. \$\endgroup\$
    – pajonk
    Commented Apr 7, 2018 at 11:15
  • \$\begingroup\$ 48 bytes: ?UCase(MonthName(Right([A1],2),1))&Mid([A1],3,2) \$\endgroup\$ Commented Apr 9, 2018 at 19:22
  • 1
    \$\begingroup\$ Turns out the Excel formula can be 46 bytes: =UPPER(TEXT(RIGHT(A1,2)*28,"MMM"))&MID(A1,3,2) \$\endgroup\$ Commented Apr 9, 2018 at 19:27
3
\$\begingroup\$

Japt -P, 14 13 bytes

ÐUò4)Åu ¸o¤Åë

Try it

ÐUò4)Åu ¸o¤Åë     :Implicit input of string U          > "201604"
Ð                 :Create Date object from
 Uò4              :  Partitions of U of length 4       > ["2016","04"]
    )             :End Date
     Å            :To date string                      > "Fri Apr 01 2016"
      u           :Uppercase                           > "FRI APR 01 2016"
        ¸         :Split on spaces                     > ["FRI","APR","01","2016"]
         o        :Modify the last element
          ¤       :  Slice off the first 2 characters  > ["FRI","APR","01","16"]
           Å      :Slice off the first element         > ["APR","01","16"]]
            ë     :Get every second element            > ["APR","16"]
                  :Implicitly join and output          > "APR16"
\$\endgroup\$
1
2
\$\begingroup\$

Oracle SQL, 49 Bytes

select to_char(to_date(n,'yyyymm'),'MONyy')from t

The data must be inserted in a table called T with a column N of type VARCHAR2(6), CHAR(6) or , only if all the years are > 1000, NUMBER

Usage:

drop table t;
create table t (n VARCHAR2(6));
insert into t values ('201604');
insert into t values ('200001');
insert into t values ('000112');
insert into t values ('123405');    

select to_char(to_date(n,'yyyymm'),'MONyy')from t;
\$\endgroup\$
6
  • \$\begingroup\$ Would it be possible to use PRINT instead of SELECT and not refer to the table using a variable as input instead ? Declaring input variable and assigning the value does not affect the byte count \$\endgroup\$ Commented Jun 23, 2016 at 12:37
  • \$\begingroup\$ Is it allowed to take input from a table? The codegolf tag info suggests that no. \$\endgroup\$
    – pajonk
    Commented Jun 23, 2016 at 13:38
  • \$\begingroup\$ @t-clausen.dk the shortest way using print is 58 chars: begin:n:=to_char(to_date(:n,'yyyymm'),'monyy');end;print n and you need 42 extra chars for a single input(VARIABLE n varchar2;BEGIN:n:='201605';END;) instead of 31 (insert into t values('000112');) if you have shorter ways please tell me. \$\endgroup\$ Commented Jun 23, 2016 at 13:39
  • \$\begingroup\$ @pajonk in this answer nobody tell me anything about the use of tables \$\endgroup\$ Commented Jun 23, 2016 at 13:41
  • 1
    \$\begingroup\$ @pajonk according to this, you can use tables for input \$\endgroup\$ Commented Jun 23, 2016 at 13:47
2
\$\begingroup\$

Microsoft SQL Server, 57 Bytes

SELECT UPPER(FORMAT(CAST('201601'+'01' AS DATE),'MMMyy'))

The Upper function is required as format does not produce Upper case months as would be expected with the MMM format pattern.

Usage:

drop table t;
create table t (n VARCHAR(6));
insert into t values ('201604');
insert into t values ('200001');
insert into t values ('000112');
insert into t values ('123405');    

SELECT UPPER(FORMAT(CAST(n+'01' AS DATE),'MMMyy')) FROM t
\$\endgroup\$
4
  • \$\begingroup\$ Just saw your answer, it is alot like mine, didn't notice it until now, removed my answer \$\endgroup\$ Commented Jun 23, 2016 at 12:23
  • \$\begingroup\$ Is it allowed to take input from a table? The codegolf tag info suggests that no. \$\endgroup\$
    – pajonk
    Commented Jun 23, 2016 at 13:38
  • \$\begingroup\$ @pajonk the answer here doesn't use input from a table, the answer is the top line and the input variable is hardcoded. Note that you can use tables as input variables as i mention earlier. The bottom part is an example how to convert several values. TSQL doesn't have STDIN nor input statements. Only way of adding data is using variables or tables. All of my answers are using those for input \$\endgroup\$ Commented Jun 23, 2016 at 14:20
  • \$\begingroup\$ Ok, thanks for clarifying. \$\endgroup\$
    – pajonk
    Commented Jun 23, 2016 at 17:03
2
\$\begingroup\$

MediaWiki Template (with ParserFunctions), 29 bytes

{{uc:{{#time:My|{{{1}}}01}}}}

Only works if English locale is chosen.

Try Sandbox

\$\endgroup\$
2
\$\begingroup\$

R, 65 bytes

function(A)paste0(toupper(month.abb[el(A:1)%%100]),substr(A,3,4))

Try it online!

Takes input as a string, leverages the constant month.abb. Uses modulus and substr to extract relevant values.

\$\endgroup\$
3
  • \$\begingroup\$ clever use of : to convert to integer! \$\endgroup\$
    – Giuseppe
    Commented Aug 22, 2018 at 20:47
  • \$\begingroup\$ @Giuseppe Not my idea :) I took it from here. I can probably apply it to a number of my existing answers! \$\endgroup\$
    – JayCe
    Commented Aug 22, 2018 at 20:51
  • \$\begingroup\$ @Giuseppe I just found a shorter hack using el - 1 less byte. \$\endgroup\$
    – JayCe
    Commented Aug 22, 2018 at 20:54
2
\$\begingroup\$

JavaScript (Node.js), 78 bytes

i=>'JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC'.match(/.../g)[i[4]+i[5]-1]+i[2]+i[3]

Try it online!

\$\endgroup\$
2
\$\begingroup\$

Headascii, 331 bytes

UUU^U[UOUODOD]ONE.++++[]]]][]]]]+O[---[]]]][]]]][U]^U]OUOUOD++E.+++^^^U[U-()D]^P(]PD++++P:-()+++++]P-P---P:-()D+++]^P(]PD+++++P:-()]PD++++++]P++P:-()D^^^+++]P(]PD---]P:-()D^^]PD^++]PD-----]P:-()D^^]PD++]P(++^^^^^D+]P:-()]PD^^D++]P(++++++]P:D^^D^]P(++++]PD---]P;UPUP!.++^^^^^U[U)D^^++++]P(++]PD-]P:R-)D^^+++]P+PD+]P:+++]P+P--P;UPUP!

Try it here! Code will need to be pasted in and executed like this:

erun("UUU^U[UOUODOD]ONE.++++[]]]][]]]]+O[---[]]]][]]]][U]^U]OUOUOD++E.+++^^^U[U-()D]^P(]PD++++P:-()+++++]P-P---P:-()D+++]^P(]PD+++++P:-()]PD++++++]P++P:-()D^^^+++]P(]PD---]P:-()D^^]PD^++]PD-----]P:-()D^^]PD++]P(++^^^^^D+]P:-()]PD^^D++]P(++++++]P:D^^D^]P(++++]PD---]P;UPUP!.++^^^^^U[U)D^^++++]P(++]PD-]P:R-)D^^+++]P+PD+]P:+++]P+P--P;UPUP!","your input here")

Headass/ascii is not particularly good at strings.

UUU^U[UOUODOD]ONE. Block 0

UU                 Discard the first two chars of input lol
  U^U[             Hold onto the last two digits of the year
      UOUODOD]O    ready MMYY for the next code block
               NE  Go to block 1
                 . Block separator


++++[]]]][]]]]+O[---[]]]][]]]][U]^U]OUOUOD++E. Block 1

++++[]]]][]]]]+O                               Save 65 for later ease of access
                [---[]]]][]]]][                -48
                               U]^             Add to first month digit and hold
                                  U]O          Add to second month digit and save
                                     UOUO      Save year digits
                                         D++E  Go to either block 1 or block 2,
                                                depending on whether the first
                                                digit of the month was 0 or 1
                                             . Block separator


+++^^^U[U-()...;UPUP!.      Block 2 (JAN-SEP)

+++^^^                      Store 9 on the accumulator
      U[                    Restore 65 from earlier
        U-()                If the second digit of the month is 1,
D]^P(]PD++++P                 Concatenate "JAN" to the string register
             :-()           Else if it's 2
+++++]P-P---P                 Concatenate "FEB" to the string register
             :-()           Else if it's 3
D+++]^P(]PD+++++P             Concatenate "MAR" to the string register
                 :-()       Else if it's 4
]PD++++++]P++P                Concatenate "APR" to the string register
              :-()          Else if it's 5
D^^^+++]P(]PD---]P            Concatenate "MAY" to the string register
                  :-()      Else if it's 6
D^^]PD^++]PD-----]P           Concatenate "JUN" to the string register
                   :-()     Else if it's 7
D^^]PD++]P(++^^^^^D+]P        Concatenate "JUL" to the string register
                      :-()  Else if it's 8
]PD^^D++]P(++++++]P           Concatenate "AUG" to the string register
                   :        Else
D^^D^]P(++++]PD---]P          Concatenate "SEP" to the string register
               ;UPUP!       Then concatenate the year digits from earlier and print!
                     .      Block separator, end of execution


++^^^^^U[U)D^...;UPUP!  Block 3 (OCT-DEC)

++^^^^^                 Store 10 on the accumulator 
       U[               Restore 65 from earlier
         U)             If the second digit of the month is 0,
D^^++++]P(++]PD-]P        Concatenate "OCT" to the string register
                  :R-)  Else if it's 1
D^^+++]P+PD+]P            Concatenate "NOV" to the string register
              :         Else
+++]P+P--P                Concatenate "DEC" to the string register
          ;UPUP!        Then concatenate the year digits from earlier and print!

\$\endgroup\$
2
\$\begingroup\$

x86-16 machine code, 64 bytes

00000000: fcad ad50 ad2d 3030 86e0 d50a be19 0103  ...P.-00........
00000010: f003 f003 f02e a52e a458 abc3 4a41 4e46  .........X..JANF
00000020: 4542 4d41 5241 5052 4d41 594a 554e 4a55  EBMARAPRMAYJUNJU
00000030: 4c41 5547 5345 504f 4354 4e4f 5644 4543  LAUGSEPOCTNOVDEC

Callable function, input at DS:SI, output buffer at ES:DI.

Listing:

FC          CLD                         ; string direction forward 
AD          LODSW                       ; skip first two chars 
AD          LODSW                       ; load YY string 
50          PUSH AX                     ; save YY string 
AD          LODSW                       ; load month string 
2D 3030     SUB  AX, '00'               ; ASCII convert month 
86 E0       XCHG AH, AL                 ; endian convert 
D5 0A       AAD                         ; word convert to index (1-12) 
BE 0116     MOV  SI, OFFSET MTBL[-3]    ; month table (1-indexed) 
03 F0       ADD  SI, AX                 ; add month offset * 3 chars 
03 F0       ADD  SI, AX 
03 F0       ADD  SI, AX
2E A5   CS: MOVSW                       ; copy first two bytes of month
2E A4   CS: MOVSB                       ; copy third byte of month to output
58          POP  AX                     ; restore YY string 
AB          STOSW                       ; write YY to output 
C3          RET 
        MTBL: 
4A 41 4E    DB  'JAN' 
46 45 42    DB  'FEB' 
4D 41 52    DB  'MAR' 
41 50 52    DB  'APR' 
4D 41 59    DB  'MAY' 
4A 55 4E    DB  'JUN' 
4A 55 4C    DB  'JUL' 
41 55 47    DB  'AUG' 
53 45 50    DB  'SEP' 
4F 43 54    DB  'OCT'
4E 4F 56    DB  'NOV' 
44 45 43    DB  'DEC' 

Sample runs:

enter image description here

\$\endgroup\$
4
  • 1
    \$\begingroup\$ Make it 62, as I guess you may want to add a CLD in front - otherwise direction is undefined. \$\endgroup\$
    – Raffzahn
    Commented Jun 21, 2023 at 19:43
  • \$\begingroup\$ In addition the code assumes that DS=CS which is only true in tiny model - which in turn doesn't need far input, does it? So to make it work the two MOVS* need a CS segment overwrite ... ending at 64 :)) \$\endgroup\$
    – Raffzahn
    Commented Jun 21, 2023 at 20:36
  • \$\begingroup\$ @Raffzahn 😒 just for that I'm not going to use MASM's long syntax for MOVS with segment override. \$\endgroup\$
    – 640KB
    Commented Jun 21, 2023 at 22:13
  • \$\begingroup\$ Fine with me - as long as the prefix gets generated. \$\endgroup\$
    – Raffzahn
    Commented Jun 22, 2023 at 5:32
2
\$\begingroup\$

Perl 5 -p, 75 bytes

$_=(1,JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DEC)[/..$/g].substr$`,2,2

Try it online!

\$\endgroup\$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.