Share via


Calcoli di data e ora

L'oggetto Oggetto Date e i metodi correlati vengono utilizzati per eseguire attività comuni relative a calendario e orologio, ad esempio la modifica e il confronto di date e il calcolo del tempo trascorso.

Impostazione di una data sulla data corrente

Quando si crea un'istanza di Oggetto Date, questa contiene un valore che rappresenta un particolare istante nel tempo, approssimato al millisecondo. Tale valore di data e ora può quindi essere letto o modificato.

Nell'esempio seguente viene illustrato come ottenere la data corrente e visualizzarla nel formato mm/gg/aa.

// Create a date object. Because no arguments are
// passed, the date object contains the current date and
// time (to the millisecond).
var dt : Date = new Date();

// Determine and display the month, day, and year.
// The getMonth method uses a zero offset for
// the month number.
var month : Number = dt.getMonth()+1;
var day : Number = dt.getDate();
var year : Number = dt.getFullYear();

print (month + "/" + day + "/" + year);

Impostazione di una data specifica

Nell'esempio seguente viene passata una data specifica al costruttore.

// Create a date object for a specific date.
var dt : Date = new Date('8/24/2009');

Il formato data viene gestito in modo abbastanza flessibile in JScript. È infatti possibile utilizzare varianti quali 8-24-2009, agosto 24, 2009 e 24 agosto 2009.

È inoltre possibile specificare un'ora, come illustrato negli esempi seguenti.

// Create a date object for a specific date and time.
// The time format is hours:minutes:seconds.
var dtA : Date = new Date('8/24/2009 14:52:10');

// Create a date object for the same date and time as in
// the previous example.
// The parameters are:
// year, month, day, hours, minutes, seconds.
// August is month 7 because January is month 0.
var dtB : Date = new Date(2009, 7, 24, 14, 52, 10);

Aggiunta e sottrazione di giorni

In un esempio precedente vengono utilizzati i metodi getMonth, getDate e getFullYear per ottenere parti della data. Un gruppo equivalente di metodi set consente di modificare il valore nell'oggetto Date.

Nell'esempio viene illustrato come è possibile impostare una data sulla data del giorno precedente. Viene ottenuta la data del giorno corrente e il giorno del mese, quindi il giorno viene impostato su un giorno precedente tramite Metodo setDate.

// Get the current day's date and day of month.
var myDate : Date = new Date();
var dayOfMonth : Number = myDate.getDate();

// Reset myDate to one day earlier.
myDate.setDate(dayOfMonth - 1);

Tramite JScript la data viene quindi incrementata al mese o all'anno successivo come richiesto. Ad esempio, se la data corrente è il 28 gennaio e si aggiungono 7 giorni, la data verrà correttamente impostata sul 4 febbraio. Nell'esempio seguente viene aggiunta una settimana alla data corrente. Viene inoltre cancellata l'ora dalla data.

var myDate : Date = new Date();
myDate.setDate(myDate.getDate() + 7);

// Clear the time.
myDate.setHours(0, 0, 0, 0);

Utilizzo di mesi e anni

L'esempio seguente contiene un ciclo che restituisce date che iniziano con 1 mese dalla data corrente. I mesi vengono incrementati correttamente all'anno successivo.

var currentDate : Date = new Date();

for(var index : int = 1; index <= 12; index++)
{
    var myDate : Date = new Date();
    myDate.setMonth(currentDate.getMonth() + index);

    print ("Month+" + index + ": " + myDate);
}

Nell'esempio seguente viene ottenuta la data corrispondente a un anno prima della data corrente.

var myDate : Date = new Date();
myDate.setFullYear (myDate.getFullYear() - 1);

Nell'esempio seguente viene ottenuto il primo giorno del mese successivo al mese corrente. Il mese viene incrementato, quindi il giorno del mese viene impostato su 1.

function GetFirstOfNextMonth() : Date
{
    var myDate : Date = new Date();
    myDate.setMonth(myDate.getMonth() + 1);
    myDate.setDate(1);

    return myDate;
}

Nell'esempio seguente viene determinato l'ultimo giorno del mese corrente. A questo scopo, viene determinato il primo del mese successivo, quindi viene sottratto un giorno.

// Determine the last day of the current month.
// The GetFirstOfNextMonth() function is in the previous example.
var myDate : Date = GetFirstOfNextMonth();
myDate.setDate (myDate.getDate() - 1);

Utilizzo di giorni della settimana

Metodo getDay (da non confondere con getDate) restituisce un valore tra 0 e 6 per indicare il giorno della settimana. Domenica corrisponde a zero, lunedì a 1 e così via. Nell'esempio seguente viene illustrato come determinare il giorno della settimana corrente.

var arDays : Array = ["Sunday", "Monday", "Tuesday",
    "Wednesday", "Thursday", "Friday", "Saturday"];

var today : Date = new Date();
var dayNum : Number = today.getDay();
var dayOfWeek : String = arDays[dayNum];

Nell'esempio seguente viene restituita la data corrispondente al venerdì prima della data corrente.

function getPreviousDayOfWeek(dayOfWeekNum : Number) : Date
{
    var dt : Date = new Date();
    if (dt.getDay() == dayOfWeekNum)
    {
        // It is currently the day of the week specified in
        // the function call. Subtract one week.
        dt.setDate(dt.getDate() - 7);
    }
    else
    {
        // Go back a day at a time until arriving
        // at the specified day of week.
        while (dt.getDay() != dayOfWeekNum)
        {
            dt.setDate(dt.getDate() - 1);
        }
    }

    return dt;
}

var friday : Number = 5;
var myDate : Date = getPreviousDayOfWeek(friday);

Nell'esempio seguente viene determinata la data per il giorno del Ringraziamento, la festività degli Stati Uniti, definita come quarto giovedì di novembre. Lo script trova l'1 novembre dell'anno corrente, quindi il primo giovedì e infine aggiunge tre settimane.

// Determine the current date and clear the time.
var myDate : Date = new Date();
myDate.setHours(0, 0, 0, 0);

// Determine November 1 of the current year.
var november : Number = 10;
myDate.setMonth(november);
myDate.setDate(1);

// Find Thursday.
var thursday : Number = 4;
while(myDate.getDay() != thursday)
{
    myDate.setDate(myDate.getDate() + 1) ;
}

// Add 3 weeks.
myDate.setDate(myDate.getDate() + 21);

Calcolo del tempo trascorso

Metodo getTime restituisce il numero di millisecondi trascorsi dalla data e ora zero di mezzanotte del 1° gennaio 1970. Per una data precedente a tale data getTime restituisce un numero negativo.

È possibile utilizzare getTime per impostare un'ora di inizio e di fine per il calcolo del tempo trascorso. Questo metodo può essere utilizzato per misurare piccole unità, ad esempio alcuni secondi, e grandi unità, ad esempio giorni.

Determinazione del tempo trascorso in secondi

In questo esempio viene calcolato il tempo trascorso in secondi. Funziona indipendentemente dalla durata dell'intervallo. I millisecondi restituiti dal metodo getTime costituiscono un valore assoluto a partire dalla data zero. Questo numero continua pertanto ad aumentare a seguito delle modifiche a minuti, ore e giorni.

Console.Write("What is your name? ");

var startTime : Date = new Date();
var name : String = Console.ReadLine();
var endTime : Date = new Date();

var elapsed : Number = 
    (endTime.getTime() - startTime.getTime()) / 1000; 

Console.WriteLine("You took " + elapsed +
    " seconds to type your name.");

Determinazione del tempo trascorso in giorni

Per utilizzare unità più facilmente gestibili, è possibile dividere i millisecondi restituiti dal metodo getTime per un numero appropriato. Ad esempio, per trasformare millisecondi in giorni, dividere il numero per 86.400.000 (1000 x 60 x 60 x 24).

Nell'esempio seguente viene illustrata la quantità di tempo trascorsa dal primo giorno dell'anno corrente. Per calcolare il tempo trascorso in giorni, ore, minuti e secondi, viene utilizzata una successione di operazioni di divisione. Non viene tenuto conto dell'ora legale.

// Set the unit values in milliseconds.
var msecPerMinute : Number = 1000 * 60;
var msecPerHour : Number = msecPerMinute * 60;
var msecPerDay : Number = msecPerHour * 24;

// Determine the current date and time.
var today : Date = new Date();

// Determine January 1, at midnight, of the current year.
var january : Number = 0;
var startOfYear : Date = new Date();
startOfYear.setMonth(january);
startOfYear.setDate(1);
startOfYear.setHours(0, 0, 0, 0);

// Determine the difference in milliseconds.
var interval : Number = today.getTime() - startOfYear.getTime();

// Calculate how many days the interval contains. Subtract that
// many days from the interval to determine the remainder.
var days : Number = Math.floor(interval / msecPerDay );
interval = interval - (days * msecPerDay );

// Calculate the hours, minutes, and seconds.
var hours : Number = Math.floor(interval / msecPerHour );
interval = interval - (hours * msecPerHour );

var minutes : Number = Math.floor(interval / msecPerMinute );
interval = interval - (minutes * msecPerMinute );

var seconds : Number = Math.floor(interval / 1000 );

// Display the result.
var msg : String = days + " days, " + hours + " hours, "
 + minutes + " minutes, " + seconds + " seconds.";

print(msg);

Definizione dell'età dell'utente

Nell'esempio seguente viene determinata l'età dell'utente in anni. L'anno di nascita viene sottratto dall'anno corrente quindi, se il compleanno non è ancora avvenuto nell'anno corrente, viene sottratto 1. Non vengono utilizzati i millisecondi trascorsi, perché la definizione di età non si basa solitamente su un rigido intervallo.

var birthday : Date = new Date("8/1/1985");
var today : Date = new Date();
var years : Number = today.getFullYear() - birthday.getFullYear();

// Reset birthday to the current year.
birthday.setFullYear(today.getFullYear());

// If the user's birthday has not occurred yet this year, subtract 1.
if (today < birthday)
{
    years--;
}
print("You are " + years + " years old.");

Nota

È necessario prestare attenzione quando si confrontano le date per assicurarsi di procedere nel modo corretto. Ulteriori informazioni sono disponibili nella sezione successiva di questo argomento.

Nell'esempio seguente viene illustrato un metodo per calcolare l'età dell'utente in mesi. Lo script include un test per determinare se il compleanno dell'utente è avvenuto nel mese corrente.

var birthday : Date = new Date("8/1/1985");
var today : Date = new Date();
var years : Number = today.getFullYear() - birthday.getFullYear();

// Determine the number of months.
var months : Number = (years * 12) +
    (today.getMonth() - birthday.getMonth());

// Adjust the months if the birthday has not occurred
// yet in the current month.
if (today.getDate() < birthday.getDate())
{
    months--;
}
print("You are " + months + " months old.");

Confronto di date

Se in JScript si confrontano oggetti utilizzando l'operatore maggiore di o minore di (<, >, <= o >=), i valori degli oggetti verranno valutati prima di eseguire il confronto. I confronti di uguaglianza funzionano in modo diverso. Se si utilizza l'operatore ==, il confronto restituirà true solo se entrambi i lati dell'operatore fanno riferimento allo stesso oggetto. L'operatore != funziona in modo analogo.

Metodo getTime restituisce il numero di millisecondi trascorsi tra la mezzanotte del 1° gennaio 1970 e il valore di ora nell'oggetto Oggetto Date. Consente di confrontare le rappresentazioni in millisecondi di due date.

Un confronto di data basato su millisecondi non funziona tuttavia correttamente se uno degli oggetti Date contiene un'ora diversa da mezzanotte.

Se si crea un oggetto Date senza includere un argomento del costruttore, l'ora associata alla data sarà l'ora corrente. Se si crea un oggetto Date per una data specifica, l'ora associata alla data sarà la mezzanotte all'inizio di quel giorno.

Nell'esempio seguente viene controllato se la data corrente corrisponde a una data specificata. Per impostare la data corrente in todayAtMidn, lo script crea un oggetto Date per l'anno, il mese e il giorno correnti.

// Determine the current date and time, and then
// determine the current date at midnight.
var now : Date = new Date(); 
var todayAtMidn : Date =
    new Date(now.getFullYear(), now.getMonth(), now.getDate());

// Set specificDate to a specified date at midnight.
var specificDate : Date = new Date("9/21/2009");

// Compare the two dates by comparing the millisecond
// representations.
if (todayAtMidn.getTime() == specificDate.getTime())
{
    print("Same");
}
else
{
    print("Different");
}

Vedere anche

Concetti

Riepilogo dei tipi di dati