utilizar tutorial qué podríamos net llamar funcion forma enviar ejecutar desde código codebehind cero asp asp.net javascript

asp.net - tutorial - enviar javascript desde c#



Calcular tiempo en JavaScript (7)

Busqué en Google el cálculo de un intervalo de tiempo en javascript y encontré esta pregunta en SO; Desafortunadamente, el texto de la pregunta y la pregunta real (que solo necesitan horas y minutos) no son lo mismo ... así que creo que llegué aquí por error.

Sin embargo, escribí una respuesta al título de la pregunta, por lo que si alguien más quiere algo que imprima algo así como "1 año y 15 minutos", entonces esto es para usted:

function formatTimespan(from, to) { var text = '''', span = { y: 0, m: 0, d: 0, h: 0, n: 0 }; function calcSpan(n, fnMod) { while (from < to) { // Modify the date, and check if the from now exceeds the to: from = from[fnMod](1); if (from <= to) { span[n] += 1; } else { from = from[fnMod](-1); return; } } } function appendText(n, unit) { if (n > 0) { text += ((text.length > 0) ? '', '' : '''') + n.toString(10) + '' '' + unit + ((n === 1) ? '''' : ''s''); } } calcSpan(''y'', ''addYears''); calcSpan(''m'', ''addMonths''); calcSpan(''d'', ''addDays''); calcSpan(''h'', ''addHours''); calcSpan(''n'', ''addMinutes''); appendText(span.y, ''year''); appendText(span.m, ''month''); appendText(span.d, ''day''); appendText(span.h, ''hour''); appendText(span.n, ''minute''); if (text.lastIndexOf('','') < 0) { return text; } return text.substring(0, text.lastIndexOf('','')) + '', and'' + text.substring(text.lastIndexOf('','') + 1); }

Tengo un control ascx de .net 2.0 con una caja de texto de inicio y finalización. La información es la siguiente:

txtStart.Text = 09/19/2008 07:00:00

txtEnd.Text = 09/19/2008 05:00:00

Me gustaría calcular el tiempo total (horas y minutos) en JavaScript y luego mostrarlo en un cuadro de texto en la página.


Las respuestas sobre todo asumen la manipulación de cadenas. Aquí hay una solución que funciona con objetos de fecha pura:

var start = new Date().getTime(); window.setTimeout(function(){ var diff = new Date(new Date().getTime() - start); // this will log 0 hours, 0 minutes, 1 second console.log(diff.getHours(), diff.getMinutes(),diff.getSeconds()); },1000);


Me gusta el enfoque K3 + KK-MOD, pero necesitaba mostrar tiempos negativos, así que hice las siguientes modificaciones:

function MillisecondsToDuration(milliseconds) { var n = Math.abs(milliseconds); var hms = ""; var dtm = new Date(); dtm.setTime(n); var d = Math.floor(n / 3600000 / 24); // KK-MOD var h = "0" + (Math.floor(n / 3600000) - (d * 24)); // KK-MOD var m = "0" + dtm.getMinutes(); var s = "0" + dtm.getSeconds(); var cs = "0" + Math.round(dtm.getMilliseconds() / 10); hms = (milliseconds < 0 ? " - " : ""); hms += (d > 0 ? d + "." : "") + h.substr(h.length - 2) + ":" + m.substr(m.length - 2) + ":"; // KK-MOD hms += s.substr(s.length - 2) + "." + cs.substr(cs.length - 2); return hms; }

También cambié el separador ''T'' a ''.'' para mis propios propósitos de formateo.

Ahora un valor negativo pasado, digamos -360000 (seis minutos negativos) producirá el siguiente resultado:

- 00:06:00


Tomé lo que @PConroy hizo y lo agregué al hacer los cálculos por usted. También agregué la expresión regular para asegurarme de que el tiempo sea parte de la cadena para crear el objeto de fecha.

<html> <head> <script type="text/javascript"> function stringToDate(string) { var matches; if (matches = string.match(/^(/d{4,4})-(/d{2,2})-(/d{2,2}) (/d{2,2}):(/d{2,2}):(/d{2,2})$/)) { return new Date(matches[1], matches[2] - 1, matches[3], matches[4], matches[5], matches[6]); } else { return null; }; } //Convert duration from milliseconds to 0000:00:00.00 format function MillisecondsToDuration(n) { var hms = ""; var dtm = new Date(); dtm.setTime(n); var h = "000" + Math.floor(n / 3600000); var m = "0" + dtm.getMinutes(); var s = "0" + dtm.getSeconds(); var cs = "0" + Math.round(dtm.getMilliseconds() / 10); hms = h.substr(h.length-4) + ":" + m.substr(m.length-2) + ":"; hms += s.substr(s.length-2) + "." + cs.substr(cs.length-2); return hms; } var beginDate = stringToDate(''2008-09-19 07:14:00''); var endDate = stringToDate(''2008-09-19 17:35:00''); var n = endDate.getTime() - beginDate.getTime(); alert(MillisecondsToDuration(n)); </script> </head> <body> </body> </html>

Esto es bastante difícil, ya que lo codifiqué bastante rápido, pero funciona. Lo probé. El cuadro de alerta mostrará 0010: 21: 00.00 (HHHH: MM: SS.SS). Básicamente, todo lo que necesita hacer es obtener los valores de sus cuadros de texto.


Una vez que los formatos de fecha de su cuadro de texto son conocidos de antemano, puede usar las funciones de fecha de Matt Kruse en Javascript para convertir las dos en una marca de tiempo, restar y luego escribir en el cuadro de texto resultante.

Igualmente, el código de entrada de fecha de JQuery para stringToDate podría adaptarse para sus propósitos: el siguiente toma una cadena en el formato "YYYY-MM-DD" y la convierte en un objeto de fecha. La marca de tiempo ( getTime() ) de estos objetos se puede usar para sus cálculos.

stringToDate: function(string) { var matches; if (matches = string.match(/^(/d{4,4})-(/d{2,2})-(/d{2,2})$/)) { return new Date(matches[1], matches[2] - 1, matches[3]); } else { return null; }; }


Use Math.floor (n / 3600000) en lugar de getUTCHours () o perderá el número de horas mayor que 24.

Por ejemplo, si tiene 126980000 milisegundos, esto debería traducirse a 0035: 16: 20.00

Si usas getUTCHours () obtienes una cadena incorrecta 0011: 16: 20.00

Mejor en su lugar, use esto (modificaciones indicadas por KK-MOD):

function MillisecondsToDuration (n) {
var hms = "";
var dtm = new Date ();
dtm.setTime (n);
var d = Math.floor (n / 3600000/24); // KK-MOD
var h = "0" + (Math.floor (n / 3600000) - (d * 24)); // KK-MOD
var m = "0" + dtm.getMinutes ();
var s = "0" + dtm.getSeconds ();
var cs = "0" + Math.round (dtm.getMilliseconds () / 10);
hms = (d> 0? d + "T": "") + h.substr (h.length - 2) + ":" + m.substr (m.length - 2) + ":"; // KK-MOD
hms + = s.substr (s.length - 2) + "." + cs.substr (cs.length - 2);
devolver hms; }

Así que ahora, 192680000 se muestra como 1T11: 16: 20.00, que es 1 día, 11 horas, 16 minutos y 20 segundos.


function stringToDate(string) { var matches; if (matches = string.match(/^(/d{4,4})-(/d{2,2})-(/d{2,2}) (/d{2,2}):(/d{2,2}):(/d{2,2})$/)) { return new Date(matches[1], matches[2] - 1, matches[3], matches[4], matches[5], matches[6]); } else { return null; }; } function getTimeSpan(ticks) { var d = new Date(ticks); return { hour: d.getUTCHours(), minute: d.getMinutes(), second: d.getSeconds() } } var beginDate = stringToDate(''2008-09-19 07:14:00''); var endDate = stringToDate(''2008-09-19 17:35:00''); var sp = getTimeSpan(endDate - beginDate); alert("timeuse:" + sp.hour + " hour " + sp.minute + " minute " + sp.second + " second ");

puede usar getUTCHours () en cambio Math.floor (n / 3600000);