54
\$\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\$
  • 5
    \$\begingroup\$ This question is very well-balanced. Both manual parsing and date libraries end up being about the same, at least in Python. \$\endgroup\$ – bkul Jun 22 '16 at 20:32
  • 10
    \$\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 Jun 23 '16 at 14:30

49 Answers 49

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\$
  • 3
    \$\begingroup\$ I don't see how this can be beaten so.. gg \$\endgroup\$ – Adnan Jun 22 '16 at 21:01
20
\$\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\$
  • 11
    \$\begingroup\$ That manual parsing is crazy. \$\endgroup\$ – Morgan Thrapp Jun 22 '16 at 20:59
  • \$\begingroup\$ @MorganThrapp I got the idea from this answer. \$\endgroup\$ – bkul Jun 22 '16 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 Jun 23 '16 at 8:39
  • 1
    \$\begingroup\$ Though this loses a byte: lambda s:" JFMAMJJASONDAEAPAUUUECOENBRRYNLGPTVC"[int(s[4:])::12]+s[2:4] \$\endgroup\$ – Henry Gomersall Jun 23 '16 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 Jun 24 '16 at 3:10
18
\$\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\$
18
\$\begingroup\$

PowerShell v2+, 49 46 bytes

(date $args[0].insert(4,'-')-U %b%y).ToUpper()

Thanks to @Joey for saving 3 bytes!

Takes input $args[0] 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 encapsulate that in parens, and 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\$
  • \$\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 Jun 24 '16 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\$ – AdmBorkBork Jun 24 '16 at 15:19
8
\$\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\$
  • \$\begingroup\$ That's pretty dang clever. \$\endgroup\$ – AdmBorkBork Jun 24 '16 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\$
6
\$\begingroup\$

Bash, 39 28 bytes

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

Thanks Digital Trauma!

\$\endgroup\$
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\$
  • \$\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\$ – bkul Jun 22 '16 at 20:32
  • 1
    \$\begingroup\$ That's fine, you beat me by 13 bytes, I'll concede. I like your manual answer, too. \$\endgroup\$ – atlasologist Jun 22 '16 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\$
  • 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\$ – Kevin Cruijssen Jun 23 '16 at 7:10
  • \$\begingroup\$ Since the challenge asks for output, I would assume a print is required as part of your function. \$\endgroup\$ – JohnWells Apr 6 '18 at 21:48
5
\$\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
    \$\begingroup\$ Wow, gj on beating everyone else in a non-golfing language! \$\endgroup\$ – Downgoat Jun 22 '16 at 20:44
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
    \$\begingroup\$ •r–ºþ¯Bê€õaPù£—^5AºüLwÇ–è•35B instead of "JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC" saves 9 bytes. \$\endgroup\$ – Adnan Jun 22 '16 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\$
  • \$\begingroup\$ First should be APR16 \$\endgroup\$ – Downgoat Jun 22 '16 at 20:34
  • \$\begingroup\$ @Upgoat And what's appearing for you? \$\endgroup\$ – nicael Jun 22 '16 at 20:35
  • 1
    \$\begingroup\$ I'm getting MAR16 \$\endgroup\$ – Downgoat Jun 22 '16 at 20:40
  • \$\begingroup\$ @Upgoat Huh, that's weird, why could it be this way? Because I get this. \$\endgroup\$ – nicael Jun 22 '16 at 20:41
  • \$\begingroup\$ For me it does show APR16, but the third test case shows only DEC for me. \$\endgroup\$ – Adnan Jun 22 '16 at 20:42
4
\$\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\$
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\$
  • 2
    \$\begingroup\$ Some cheap tricks - delete the #include, define m as a parameter - main(m), \$\endgroup\$ – ugoren Jun 23 '16 at 15:07
  • 2
    \$\begingroup\$ Also, the %.3s format saves the null termination. \$\endgroup\$ – ugoren Jun 23 '16 at 15:09
  • \$\begingroup\$ Thanks @ugoren! I also changed "%4s%2d" to "%4s%d". \$\endgroup\$ – Marco Jun 23 '16 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 Apr 8 '18 at 13:49
4
\$\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\$
  • \$\begingroup\$ I made one in 66 bytes with the same atob technique, but I can't copy it out \$\endgroup\$ – Bálint Jun 22 '16 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 Jun 22 '16 at 20:36
  • \$\begingroup\$ You could get the month's name with (Date(0,a[4]- -a[5])+"").substr(4,3) \$\endgroup\$ – Bálint Jun 22 '16 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 Jun 22 '16 at 22:55
  • 1
    \$\begingroup\$ new Date(0,a[4]+a[5]-1)+"" => new Date(0,a[4]+a[5]-1)+0 \$\endgroup\$ – l4m2 Apr 7 '18 at 0:53
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\$
  • \$\begingroup\$ You can leave off return type information for lambdas, i.e C(string s)=>... \$\endgroup\$ – cat Jun 24 '16 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\$
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\$
  • \$\begingroup\$ I think you can shorten it if you remove the import and instead directly refer to it with java.text.SimpleDateFormat. \$\endgroup\$ – Frozn Jun 23 '16 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\$ – Kevin Cruijssen Jun 23 '16 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 Jun 25 '16 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\$ – Kevin Cruijssen Jun 25 '16 at 10:32
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\$
  • \$\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\$ – t-clausen.dk Jun 23 '16 at 12:37
  • \$\begingroup\$ Is it allowed to take input from a table? The codegolf tag info suggests that no. \$\endgroup\$ – pajonk Jun 23 '16 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\$ – Giacomo Garabello Jun 23 '16 at 13:39
  • \$\begingroup\$ @pajonk in this answer nobody tell me anything about the use of tables \$\endgroup\$ – Giacomo Garabello Jun 23 '16 at 13:41
  • 1
    \$\begingroup\$ @pajonk according to this, you can use tables for input \$\endgroup\$ – t-clausen.dk Jun 23 '16 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\$
  • \$\begingroup\$ Just saw your answer, it is alot like mine, didn't notice it until now, removed my answer \$\endgroup\$ – t-clausen.dk Jun 23 '16 at 12:23
  • \$\begingroup\$ Is it allowed to take input from a table? The codegolf tag info suggests that no. \$\endgroup\$ – pajonk Jun 23 '16 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\$ – t-clausen.dk Jun 23 '16 at 14:20
  • \$\begingroup\$ Ok, thanks for clarifying. \$\endgroup\$ – pajonk Jun 23 '16 at 17:03
2
\$\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\$
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\$
  • \$\begingroup\$ clever use of : to convert to integer! \$\endgroup\$ – Giuseppe Aug 22 '18 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 Aug 22 '18 at 20:51
  • \$\begingroup\$ @Giuseppe I just found a shorter hack using el - 1 less byte. \$\endgroup\$ – JayCe Aug 22 '18 at 20:54
1
\$\begingroup\$

J, 70 bytes

4(}.((,~(_3]\'JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC'){~1-~".)~2&}.){.)]

Usage

   f =: 4(}.((,~(_3]\'JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC'){~1-~".)~2&}.){.)]
   f '201604'
APR16
   f '200001'
JAN00
   f '000112'
DEC01
   f '123405'
MAY34

Explanation

4(}.((,~(_3]\'...'){~1-~".)~2&}.){.)] Input: s
                                    ] Identity function, gets the value s
4                                     The constant 4
                                 {.   Take the first 4 chars from s
                            2&}.      Drop the first 2 (Take the last 2) to get the year
  }.                                  Drop the first 4 chars from s to get the month
                        ".            Parse the month substring as a number
                     1-~              Subtract 1 from it
             '...'                    List of MMM month names
         _3]\                         Split the list into nonoverlapping sublists of size 3
      ,~                              Join the MMM month name with the year and return
\$\endgroup\$
1
\$\begingroup\$

Pyth, 39 bytes

Hexdump:

0000000: 2b 40 63 2e 22 41 59 12 56 0a 7c bd 93 e3 1c 07 +@c."AY.V.|.....
0000010: e3 d4 d9 ed 5b 49 02 cd b4 92 83 86 22 33 73 3e ....[I......"3s>
0000020: 32 7a 3a 7a 32 20 34                            2z:z2 4

Test suite.

\$\endgroup\$
1
\$\begingroup\$

jq, 35 characters

(34 characters code + 1 character command-line option.)

(Just tried whether the ^ trick used by Digital Trauma in his Bash answer works in jq too. Works. Now you know who inspired the most important character of this answer. (The alternative is to use the ascii_upcase function.))

strptime("%Y%m")|strftime("%^b%y")

Sample run (Option -R used only in this sample to pass all test cases.)

bash-4.3$ jq -Rr 'strptime("%Y%m")|strftime("%^b%y")' <<END
201604
200001
000112
123405
END
APR16
JAN00
DEC01
MAY34

On-line test: (Passing -R through URL is not supported – so input passed as JSON string literal. Passing -r through URL is not supported – check Raw Output yourself.)

\$\endgroup\$
1
\$\begingroup\$

Factor, 82 78 bytes

[ [ 2 tail* 10 base> month-abbreviation ] [ 4 head 2 tail ] bi append >upper ]

Eshplained:

[                    ! new anonymouse function block (quotation)
  [                  ! new quotation 
    2 tail*          ! "201604" -> "04"
    10 base>         ! "04"     -> 4
    month-abbreviation ! 4 -> "Apr"
  ]                  ! end quotation
  [                  ! new quotation
    4 head           ! "201604" -> "2016"
    2 tail           ! "2016"   -> "16" 
  ]                  ! end quotation
  bi                 ! bifurcate two quotations to TOS
  append             ! "Apr" "16" -> "Apr16"
  >upper             ! "Apr16"    -> "APR16"
]                    ! end quotation
\$\endgroup\$
1
\$\begingroup\$

PHP, 78 bytes

<?=fscanf(STDIN,"%4d%d",$y,$m)?strtoupper(date("My",mktime(0,0,0,$m,1,$y))):0;

The "year 2038 problem" may occur on some computers, as here. But not in others, as here.

\$\endgroup\$
  • \$\begingroup\$ @Titus, please don't try to edit other peoples' posts if there are problems and insert your own solutions; instead, please comment on the answer OR create a new answer yourself. \$\endgroup\$ – Value Ink Jun 25 '16 at 7:32
1
\$\begingroup\$

Swift 2.2, 149 bytes

let f = NSDateFormatter(),g = NSDateFormatter();f.dateFormat = "yyyyMM";g.dateFormat = "MMMyy"
g.stringFromDate(f.dateFromString(i)!).uppercaseString

Trying to get this shorter than Kotlin... It's a shame NSDateFormatter doesn't have an initializer that sets its dateFormat. NSDateFormatter also does not have a default dateFormat value, causing additional losses.

Swift 3, 136 bytes

let f = DateFormatter(),g = DateFormatter();f.dateFormat = "yyyyMM";g.dateFormat = "MMMyy"
g.string(from: f.date(from: i)!).uppercased()

Thanks to the removal of the NS prefix on some classes, I was able to make the Swift 3 answer a little shorter. Still not shorter than Kotlin though...

Test function and cases:

import Foundation
import XCTest

func dateConverter(i: String) -> String? {
    let f = DateFormatter(),g = DateFormatter();f.dateFormat = "yyyyMM";g.dateFormat = "MMMyy"

    if let date = f.date(from: i) {
        return g.string(from: date).uppercased()
    }

    return nil
}

XCTAssert(dateConverter(i: "201604") == "APR16")
XCTAssert(dateConverter(i: "200001") == "JAN00")
XCTAssert(dateConverter(i: "000112") == "DEC01")
XCTAssert(dateConverter(i: "123405") == "MAY34")
\$\endgroup\$
1
\$\begingroup\$

R, 154 150 114 112 bytes

Takes six digit input into "b", separates the first four digits from the last two digits, abbreviates the 2-digit month and makes it uppercase, and concatenates it with the 3rd and 4th digit.

Golfed:

function(b){h=substr;i=sprintf;o="%06d";cat(toupper(month.abb[as.numeric(h(i(o,b),5,6))]),h(i(o,b),3,4),sep="")}

Ungolfed:

function(b){
   h=substr;i=sprintf;o="%06d";

   cat(
      toupper(month.abb[as.numeric(h(i(o,b),5,6))]),
      h(i(o,b),3,4),
   sep="")
}

EDITS: replaced duplicitous names with variables; fixed me being stupid. -2 bytes by turning function anonymous (thanks, cat).

\$\endgroup\$
  • \$\begingroup\$ Nice answer! You can leave off the a= for an anonymous function \$\endgroup\$ – cat Jun 24 '16 at 17:56
  • \$\begingroup\$ @cat I'm not too familiar with anonymous functions but wouldn't I need to add parentheses at the beginning and end of the function if I removed the a= ? Something like this: (function(m) {a=3;m*a})(10) \$\endgroup\$ – a soft pillow Jun 24 '16 at 18:52
  • 1
    \$\begingroup\$ Nope, function(b){h=substr;i=sprintf;o="%06d";cat(toupper(month.abb[as.numeric(h(i(o,b),5,6))]),h(i(o,b),3,4),sep="")} is a function object all on its own. \$\endgroup\$ – cat Jun 24 '16 at 19:17
  • \$\begingroup\$ This doesn't appear to work. on RStudio with R 3.2.3 (2015-12-10) I get Error in i(o, b) : invalid format '%06d'; use format %s for character objects \$\endgroup\$ – cat Jun 24 '16 at 19:18
  • \$\begingroup\$ @cat Darn new versions messing everything up! I'm on RStudio running R version 3.1.1 (2014-07-10) and it works fine. How does this work here, should I get the new version and change up the code? Also thanks for the anonymous function tip! \$\endgroup\$ – a soft pillow Jun 24 '16 at 19:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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