2 votos

AppleScript Formato y cálculo de la fecha

Trabajo con tres formatos de fecha,

1. 04/18/2015 (PS la fecha de mi sistema no es la misma sino DD/MM/AA)

2. 2 de junio de 2012 pero convertido al 1er formato mediante el código siguiente

3. Sábado 24 de marzo de 2018 (fecha actual)

Acabo de crear el script de abajo para convertir ambas fechas en el mismo formato:

set creationDate to "March 23rd, 2018"
set CreationDay to ""
set Creationmonth to ""
set Creationyear to ""

if creationDate contains "1st" then
    set CreationDay to "1"
end if
if creationDate contains "2nd" then
    set CreationDay to "2"
end if
if creationDate contains "3rd" then
    set CreationDay to "3"
end if
if creationDate contains "4th" then
    set CreationDay to "4"
end if
if creationDate contains "5th" then
    set CreationDay to "5"
end if
if creationDate contains "6th" then
    set CreationDay to "6"
end if
if creationDate contains "7th" then
    set CreationDay to "7"
end if
if creationDate contains "8th" then
    set CreationDay to "8"
end if
if creationDate contains "9th" then
    set CreationDay to "9"
end if
if creationDate contains "10th" then
    set CreationDay to "10"
end if
if creationDate contains "11th" then
    set CreationDay to "11"
end if
if creationDate contains "12th" then
    set CreationDay to "12"
end if
if creationDate contains "13th" then
    set CreationDay to "13"
end if
if creationDate contains "14th" then
    set CreationDay to "14"
end if
if creationDate contains "15th" then
    set CreationDay to "15"
end if
if creationDate contains "16th" then
    set CreationDay to "16"
end if
if creationDate contains "17th" then
    set CreationDay to "17"
end if
if creationDate contains "18th" then
    set CreationDay to "18"
end if
if creationDate contains "19th" then
    set CreationDay to "19"
end if
if creationDate contains "20th" then
    set CreationDay to "20"
end if
if creationDate contains "21st" then
    set CreationDay to "21"
end if
if creationDate contains "22nd" then
    set CreationDay to "22"
end if
if creationDate contains "23rd" then
    set CreationDay to "23"
end if
if creationDate contains "24th" then
    set CreationDay to "24"
end if
if creationDate contains "25th" then
    set CreationDay to "25"
end if
if creationDate contains "26th" then
    set CreationDay to "26"
end if
if creationDate contains "27th" then
    set CreationDay to "27"
end if
if creationDate contains "28th" then
    set CreationDay to "28"
end if
if creationDate contains "29th" then
    set CreationDay to "29"
end if
if creationDate contains "30th" then
    set CreationDay to "30"
end if
if creationDate contains "31st" then
    set CreationDay to "31"
end if

if creationDate contains "2018" then
    set Creationyear to "2018"
end if
if creationDate contains "2017" then
    set Creationyear to "2017"
end if
if creationDate contains "2016" then
    set Creationyear to "2016"
end if
if creationDate contains "2015" then
    set Creationyear to "2015"
end if
if creationDate contains "2014" then
    set Creationyear to "2014"
end if
if creationDate contains "2013" then
    set Creationyear to "2013"
end if
if creationDate contains "2012" then
    set Creationyear to "2012"
end if
if creationDate contains "2011" then
    set Creationyear to "2011"
end if
if creationDate contains "2010" then
    set Creationyear to "2010"
end if
if creationDate contains "2009" then
    set Creationyear to "2009"
end if
if creationDate contains "2008" then
    set Creationyear to "2008"
end if
if creationDate contains "2007" then
    set Creationyear to "2007"
end if
if creationDate contains "2006" then
    set Creationyear to "2006"
end if
if creationDate contains "2005" then
    set Creationyear to "2005"
end if
if creationDate contains "2004" then
    set Creationyear to "2004"
end if
if creationDate contains "2003" then
    set Creationyear to "2003"
end if

if creationDate contains "January" then
    set Creationmonth to "01"
end if
if creationDate contains "February" then
    set Creationmonth to "02"
end if
if creationDate contains "March" then
    set Creationmonth to "03"
end if
if creationDate contains "April" then
    set Creationmonth to "04"
end if
if creationDate contains "May" then
    set Creationmonth to "05"
end if
if creationDate contains "June" then
    set Creationmonth to "06"
end if
if creationDate contains "July" then
    set Creationmonth to "07"
end if
if creationDate contains "Agust" then
    set Creationmonth to "08"
end if
if creationDate contains "September" then
    set Creationmonth to "09"
end if
if creationDate contains "October" then
    set Creationmonth to "10"
end if
if creationDate contains "November" then
    set Creationmonth to "11"
end if
if creationDate contains "December" then
    set Creationmonth to "12"
end if

set CreationfinalDate to CreationDay & "/" & Creationmonth & "/" & Creationyear
return CreationfinalDate

Pregunta 1: ¿Cómo puedo convertir la fecha número 3 (que es la fecha actual) al mismo formato

(Sé cómo devolver como una cadena, pero no de otra manera)

set myDate to date string of (current date)

Pregunta 2: ¿puedo crear un script que me diga si la diferencia entre la fecha 2 y la fecha 3 están dentro de 60 días o fuera de 60 días?

7voto

qarma Puntos 71

Pregunta 1: En lugar de tomarse la molestia de obtener el current date sólo para convertirlo a otro formato, puedes obtenerlo en el formato correcto directamente con un comando bash:

    do shell script "date +'%m/%d/%Y'"
        --> 03/24/2018

Pregunta 2: En primer lugar, cambie el formato de la fecha para que su sistema la reconozca. En tu caso (y en el mío), es dd/mm/yyyy :

    set [M, ordinal, Y] to the words of "June 2nd, 2012"

    set the text item delimiters to {"st", "nd", "rd", "th"}
    set cardinal to (first text item of ordinal) --> "2"
    set cardinal to text -1 thru -2 of ("0" & cardinal) --> "02"

    set the text item delimiters to space
    set date_string to {M, cardinal, Y} as text

    -- date -j -f '%B %d %Y' 'June 02 2012' +'%d/%m/%Y'
    set command to {¬
        "date -j -f '%B %d %Y'", ¬
        quoted form of the date_string, ¬
        "+'%d/%m/%Y'"}

    do shell script (command as text) --> "02/06/2012"

A continuación, reste una fecha a la fecha actual y divídala por days para obtener el número de días entre las dos fechas:

    ((current date) - (date result)) / days
        --> 2121.627

PS. Puede utilizar ese mismo comando del shell para convertir la fecha a su primer formato, mm/dd/yyyy simplemente cambiando %d y %m al final del command cadena.


ADENDA:

También he pensado en mostrarte cómo convertir la tercera cadena de fecha al formato que desees utilizando AppleScript puro. Se puede hacer bastante bastante elegante, en realidad:

    set today to "Saturday 24 March 2018"

    set [_day, _month, _year] to [day, month, year] of date today
        --> {24, March, 2018}

    set _month to _month * 1 --> 3
    set _month to text -1 thru -2 of ("0" & _month) --> "03"

    set the text item delimiters to "/"
    return {_month, _day, _year} as string
        --> "03/24/2018"

Nota para otros usuarios: El código de este apéndice puede o no funcionarle, dependiendo de la configuración de su sistema. AppleScript es notoriamente quisquilloso sobre lo que reconocerá o no como una cadena de fecha. El OP y yo parece que tienen similares o idénticos Lengua y región ajustes de fecha, lo que permite que la variable today sea interpretado correctamente como una fecha por AppleScript, mientras que el mismo código ejecutado en un sistema diferente arrojaría un error.

Para adaptar el código a su propio sistema, ejecute primero el comando get date string of (current date) para obtener una vista previa del formato de fecha utilizado por su sistema y, a continuación, cambie la declaración de la variable por today para que coincida. Como alternativa, establezca la variable today a the date string of (current date) .

1 votos

La información que buscaba no se encontraba en este hilo, pero tenía que señalar qué cosa más bonita y ordenada. set _month to text -1 thru -2 of ("0" & _month) es. Tardé un momento en apreciar plenamente su ingenio. Hurra.

0voto

Steve Evans Puntos 155

Coacciona a tu cita con un AppleScript date puede realizar cálculos como set myNewDate to myDate + (2 * days) . Para más cálculos de fechas, véase Cálculos de fecha y hora con AppleScript y Guía del lenguaje AppleScript - Fecha .

A continuación se muestra un enfoque alternativo para analizar el tercer formato de fecha, más verboso. Este enfoque utiliza subrutinas para dividir y recortar la entrada. No es completo, pero esperamos que sea útil:

set myDate to "March 1st, 2018"
set myComponents to my split(myDate, " ")

set myDay to second item of myComponents
set myDay to trim(",rdsth", myDay) as integer

set myMonth to first item of myComponents
set myYear to last item of myComponents as integer

-- ...myDay, myMonth, and myYear are usable

-- http://erikslab.com/2007/08/31/applescript-how-to-split-a-string/
on split(theString, theDelimiter)
    -- save delimiters to restore old settings
    set oldDelimiters to AppleScript's text item delimiters
    -- set delimiters to delimiter to be used
    set AppleScript's text item delimiters to theDelimiter
    -- create the array
    set theArray to every text item of theString
    -- restore the old setting
    set AppleScript's text item delimiters to oldDelimiters
    -- return the result
    return theArray
end split

-- https://macscripter.net/viewtopic.php?id=18519
on trim(theseCharacters, someText)
    -- Lazy default (AppleScript doesn't support default values)
    if theseCharacters is true then set theseCharacters to ¬
        {" ", tab, ASCII character 10, return, ASCII character 0}

    repeat until first character of someText is not in theseCharacters
        set someText to text 2 thru -1 of someText
    end repeat

    repeat until last character of someText is not in theseCharacters
        set someText to text 1 thru -2 of someText
    end repeat

    return someText
end trim

0 votos

Que el trabajo también, pero esto tiene más sentido, supongo, sin embargo, establecer myFinalDae a myMonth & "/" & myDay & "/" & myYear retorno "March/1/2018" Tengo una mejor mirada en un segundo

AppleAyuda.com

AppleAyuda es una comunidad de usuarios de los productos de Apple en la que puedes resolver tus problemas y dudas.
Puedes consultar las preguntas de otros usuarios, hacer tus propias preguntas o resolver las de los demás.

Powered by:

X