elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: AIO elhacker.NET 2021 Compilación herramientas análisis y desinfección malware


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP) (Moderador: kub0x)
| | | |-+  convertir calendario gregoriano a gps
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: convertir calendario gregoriano a gps  (Leído 2,983 veces)
rochro

Desconectado Desconectado

Mensajes: 42


Ver Perfil
convertir calendario gregoriano a gps
« en: 10 Febrero 2015, 17:34 pm »

Hola a todos, quisiera que me ayuden en poder adaptar el código para lo siguiente:

simulación calendario

ver contenido:  http://gps.topografia.upm.es/www/calactal.htm

tengo este codigo:

Código
  1. Private Sub DateTimePicker1_ValueChanged(sender As Object, e As EventArgs) Handles DateTimePicker1.ValueChanged
  2.  
  3.        Dim vDia As String = DateTimePicker1.Value.Day
  4.        Dim vMes As String = DateTimePicker1.Value.Month
  5.        Dim vAño As String = DateTimePicker1.Value.Year
  6.  
  7.        txtday.Text = Juliandate(DateTimePicker1.Value)
  8.  
  9.    End Sub
  10.  
  11. Public Function Juliandate(ByVal dtdate As Date) As Integer
  12.  
  13.        Dim dtfirstmonthDAY As Date
  14.        Dim dttimepicker As Date
  15.  
  16.        dtfirstmonthDAY = DateSerial(Year(dtdate), 1, 1)
  17.        dttimepicker = dtdate
  18.        Return CInt(DateDiff(DateInterval.Day, dtfirstmonthDAY, dttimepicker)) + 1
  19.  
  20.    End Function
  21.  
  22. Friend ReadOnly GPSDictionary As Dictionary(Of Integer, Integer) = Me.GetGPSDictionary
  23.  
  24.    Private Function GetGPSDictionary() As Dictionary(Of Integer, Integer)
  25.  
  26.        Dim ThisYear As Integer = vAño
  27.        Dim DaysInThisYear As Integer = (From month As Integer In Enumerable.Range(1, 12)
  28.                                         Select DateTime.DaysInMonth(ThisYear, month)).Sum
  29.        Dim GPSWeeks As IEnumerable(Of Integer) = Enumerable.Range(1773 - 1, 1825)
  30.        Dim Result As New Dictionary(Of Integer, Integer)
  31.        For Day As Integer = 1 To DaysInThisYear
  32.            Result.Add(Day, GPSWeeks(DatePart(DateInterval.WeekOfYear,
  33.                                              New DateTime(ThisYear, 1, 1).AddDays(Day - 1))))
  34.        Next Day
  35.        Return Result
  36.  
  37.    End Function

La observación está en la elección de años diferentes. Se que se le está poniendo un limite 1773 a 1825 que corresponde al 2014 pero que podria hacer en caso que quisiera otro año. Que otra lógica se podría pensar.

Gracias por su apoyo.


 :-*
  


« Última modificación: 10 Febrero 2015, 23:06 pm por rochro » En línea

engel lex
Moderador Global
***
Desconectado Desconectado

Mensajes: 15.514



Ver Perfil
Re: convertir de día/mes a un numero correlativo
« Respuesta #1 en: 10 Febrero 2015, 17:36 pm »

hola,

Qué llevas hecho y qué no te permite resolverlo (que no sabes)

recuerda que el foro es para responder dudas pountuales, no entregar tareas hechas


En línea

El problema con la sociedad actualmente radica en que todos creen que tienen el derecho de tener una opinión, y que esa opinión sea validada por todos, cuando lo correcto es que todos tengan derecho a una opinión, siempre y cuando esa opinión pueda ser ignorada, cuestionada, e incluso ser sujeta a burla, particularmente cuando no tiene sentido alguno.
rochro

Desconectado Desconectado

Mensajes: 42


Ver Perfil
Re: convertir de día/mes a un numero correlativo
« Respuesta #2 en: 10 Febrero 2015, 23:08 pm »

hola,

Qué llevas hecho y qué no te permite resolverlo (que no sabes)

recuerda que el foro es para responder dudas pountuales, no entregar tareas hechas

Disculpa .. ya agregué el código.
Gracias por la atención prestada.
En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: convertir calendario gregoriano a gps
« Respuesta #3 en: 11 Febrero 2015, 13:33 pm »

Vaya, recuerdo que estabas haciendo esa tarea en VBS y te ayudé a resolver el algoritmo y otras dudas que tenias, me alegra saber que has trasladado el trabajo a un lenguaje más óptimo como Vb.Net :)



Hay varias cosas muy incorrectas en el código que has mostrado.


1)
El segundo parámetro de la función "Enumerable.Range" es un contador, no es el final del rango inicial.

Por lo tanto, en esta instrucción estás generando 1825 valores innecesarios, empezando desde el valor 1772 y acabando en el valor 3596:
Citar
Código
  1. Enumerable.Range(1773 - 1, 1825)

Cuando lo que deberías crear es un rango de 53 valores correspondientes a los 53 valores de las semanas GPS de ese año, de esta manera:
Código
  1. Enumerable.Range(1773 - 1, 53)


2)
Los indices en .Net empiezan por 0, no es correcto empezar por 1
Citar
Código
  1.        For Day As Integer = 1 To DaysInThisYear
  2.           Result.Add(Day, GPSWeeks(DatePart(DateInterval.WeekOfYear,
  3.                                             New DateTime(ThisYear, 1, 1).AddDays(Day - 1))))
  4.       Next Day

Déjalo así:
Código
  1.        For day As Integer = 0 To (totalDaysInYear - 1)
  2.            result.Add(day, gpsWeeks(DatePart(DateInterval.WeekOfYear,
  3.                                              New DateTime(year, 1, 1).AddDays(day))))
  4.        Next day
  5.  


3)
A la función "JulianDate" le das demasiadas vueltas utilizando wrappers de vb6, cuando puedes simplificarlo de esta manera:
Código
  1.    Public Function JulianDate(ByVal [date] As Date) As Integer
  2.  
  3.        Return [date].Subtract(New Date([date].Year, 1, 1)).Days + 1
  4.  
  5.    End Function


4)
Las variables Día, Més, y Año (que por cierto, no deberías utilizar caracteres especiales en el nombramiento de las variables), yo las adaptaría en propiedades para añadirle mayor movilidad, y control de errores:
Código
  1.    Friend ReadOnly Property GPSDictionary(ByVal datePicker As DateTimePicker) As Dictionary(Of Integer, Integer)
  2.        Get
  3.            If datePicker IsNot Nothing Then
  4.                Return Me.GetGPSDictionary(datePicker)
  5.            Else
  6.                Throw New ArgumentNullException("datePicker")
  7.                Return Nothing
  8.            End If
  9.        End Get
  10.    End Property
  11.  
  12.    Friend ReadOnly Property Day(ByVal datePicker As DateTimePicker) As Integer
  13.        Get
  14.            If datePicker IsNot Nothing Then
  15.                Return datePicker.Value.Day
  16.            Else
  17.                Throw New ArgumentNullException("datePicker")
  18.                Return -1
  19.            End If
  20.        End Get
  21.    End Property
  22.  
  23.    Friend ReadOnly Property Month(ByVal datePicker As DateTimePicker) As Integer
  24.        Get
  25.            If datePicker IsNot Nothing Then
  26.                Return datePicker.Value.Month
  27.            Else
  28.                Throw New ArgumentNullException("datePicker")
  29.                Return -1
  30.            End If
  31.        End Get
  32.    End Property
  33.  
  34.    Friend ReadOnly Property Year(ByVal datePicker As DateTimePicker) As Integer
  35.        Get
  36.            If datePicker IsNot Nothing Then
  37.                Return datePicker.Value.Year
  38.            Else
  39.                Throw New ArgumentNullException("datePicker")
  40.                Return -1
  41.            End If
  42.        End Get
  43.    End Property


5)
El event-handler "DateTimePicker1_ValueChanged" quedaría así:
Código
  1.    Private Sub DateTimePicker1_ValueChanged(ByVal sender As Object, ByVal e As EventArgs) _
  2.    Handles DateTimePicker1.ValueChanged
  3.  
  4.        Me.txtday.Text = CStr(Me.JulianDate(DirectCast(sender, DateTimePicker).Value))
  5.  
  6.    End Sub



Respondiendo a tu pregunta principal, puedes hacer que la función pida una fecha como parámetro, para poder trabajar con el año de la fecha, y así puedes asignar el rango equivalente al año específico:

Código
  1.    Private Function GetGPSDictionary(ByVal datePicker As DateTimePicker) As IDictionary(Of Integer, Integer)
  2.  
  3.        Dim year As Integer = Me.Year(datePicker)
  4.        Dim totalDaysInYear As Integer = New Date(year, 1, 1).AddYears(1).Subtract(New Date(year, 1, 1)).Days
  5.        Dim gpsWeeks As IEnumerable(Of Integer)
  6.        Dim result As IDictionary(Of Integer, Integer)
  7.  
  8.        Select Case year
  9.  
  10.            Case 2014
  11.                gpsWeeks = Enumerable.Range(1773 - 1, 53)
  12.  
  13.            Case 2015
  14.                gpsWeeks = Enumerable.Range(1825 - 1, 53)
  15.  
  16.            Case 2016
  17.                gpsWeeks = Enumerable.Range(1877 - 1, 53)
  18.  
  19.            Case Else ' Año desconocido, lanzar excepción.
  20.                Throw New NotImplementedException("En este ejemplo no se ha implementado el calendario GPS para el año especificado.")
  21.  
  22.        End Select
  23.  
  24.        result = New Dictionary(Of Integer, Integer)
  25.        For day As Integer = 0 To (totalDaysInYear - 1)
  26.            result.Add(day, gpsWeeks(DatePart(DateInterval.WeekOfYear,
  27.                                              New DateTime(year, 1, 1).AddDays(day))))
  28.        Next day
  29.  
  30.        Return result
  31.  
  32.    End Function

De todas formas, quizás podrías automatizar la tarea ya que en un principio y por lo que he visto cada rango parece constar de 53 valores correspondientes a las 53 semanas del calendario GPS en un año con 365 dias, así que yo habia pensado en algo así, el problema es que no da el resultado que debería dar (1820 en vez de 1825) pero si incremento el startingYear a 2010 y el startingGPSWeek al 1564 de ese año 2010 si que da el resultado esperado, así que algún detalle estoy omitiendo respecto a los calendarios y los días en los años, pero te dejo la idea por si quieres perfeccionarla:

Código
  1.        Dim startingYear As Integer = 1994
  2.        Dim startingGPSWeek As Integer = 723
  3.  
  4.        Dim a As Integer
  5.        For x As Integer = startingYear To (year - 1)
  6.  
  7.            Select Case New Date(x, 1, 1).AddYears(1).Subtract(New Date(x, 1, 1)).Days
  8.  
  9.                Case 365 ' days in year
  10.                    startingGPSWeek += 52
  11.  
  12.                Case 366 ' days in year
  13.                    startingGPSWeek += 53
  14.  
  15.            End Select
  16.  
  17.        Next
  18.  
  19.        MsgBox(startingGPSWeek)
  20.    ...
  21.            gpsWeeks = Enumerable.Range(startingGPSWeek - 1, 53) ' ajustar el 53 al numero real de semanas GPS
  22.    ...
  23.  

EDITO: Por supuesto cabe mencionar que otra alternativa sería obtener el código fuente de la página del año en cuestión y parsearlo, pero me resulta innecesario.



Bueno, te dejo el código completo con las modificaciones que mencioné, no estoy seguro de haber comprobado correctamente que todos los días devuelvan el valor esperado:

Código
  1. Public Class TestForm
  2.  
  3. #Region " Properties "
  4.  
  5.    ''' <summary>
  6.    ''' Gets the GPS dictionary according to the specified <see cref="DateTimePicker"/> current year.
  7.    ''' </summary>
  8.    Friend ReadOnly Property GPSDictionary(ByVal datePicker As DateTimePicker) As IDictionary(Of Integer, Integer)
  9.        Get
  10.            If datePicker IsNot Nothing Then
  11.                Return Me.GetGPSDictionary(datePicker)
  12.            Else
  13.                Throw New ArgumentNullException("datePicker")
  14.                Return Nothing
  15.            End If
  16.        End Get
  17.    End Property
  18.  
  19.    ''' <summary>
  20.    ''' Gets the day of the specified <see cref="DateTimePicker"/>.
  21.    ''' </summary>
  22.    ''' <value>The year.</value>
  23.    ''' <exception cref="System.ArgumentNullException">datePicker</exception>
  24.    Friend ReadOnly Property Day(ByVal datePicker As DateTimePicker) As Integer
  25.        Get
  26.            If datePicker IsNot Nothing Then
  27.                Return datePicker.Value.Day
  28.            Else
  29.                Throw New ArgumentNullException("datePicker")
  30.                Return -1
  31.            End If
  32.        End Get
  33.    End Property
  34.  
  35.    ''' <summary>
  36.    ''' Gets the month of the specified <see cref="DateTimePicker"/>.
  37.    ''' </summary>
  38.    ''' <value>The year.</value>
  39.    ''' <exception cref="System.ArgumentNullException">datePicker</exception>
  40.    Friend ReadOnly Property Month(ByVal datePicker As DateTimePicker) As Integer
  41.        Get
  42.            If datePicker IsNot Nothing Then
  43.                Return datePicker.Value.Month
  44.            Else
  45.                Throw New ArgumentNullException("datePicker")
  46.                Return -1
  47.            End If
  48.        End Get
  49.    End Property
  50.  
  51.    ''' <summary>
  52.    ''' Gets the year of the specified <see cref="DateTimePicker"/>.
  53.    ''' </summary>
  54.    ''' <value>The year.</value>
  55.    ''' <exception cref="System.ArgumentNullException">datePicker</exception>
  56.    Friend ReadOnly Property Year(ByVal datePicker As DateTimePicker) As Integer
  57.        Get
  58.            If datePicker IsNot Nothing Then
  59.                Return datePicker.Value.Year
  60.            Else
  61.                Throw New ArgumentNullException("datePicker")
  62.                Return -1
  63.            End If
  64.        End Get
  65.    End Property
  66.  
  67. #End Region
  68.  
  69. #Region " Event-Handlers "
  70.  
  71.    ''' <summary>
  72.    ''' Handles the ValueChanged event of the DateTimePicker1 control.
  73.    ''' </summary>
  74.    ''' <param name="sender">The source of the event.</param>
  75.    ''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  76.    Private Sub DateTimePicker1_ValueChanged(ByVal sender As Object, ByVal e As EventArgs) _
  77.    Handles DateTimePicker1.ValueChanged
  78.  
  79.        Dim datePicker As DateTimePicker = DirectCast(sender, DateTimePicker)
  80.  
  81.        Me.txtday.Text = CStr(Me.JulianDate(datePicker.Value))
  82.  
  83.        'Try
  84.        '    ' MsgBox(GPSDictionary(datePicker)(1))
  85.        '    MsgBox(GPSDictionary(datePicker)(3))
  86.  
  87.        'Catch ex As Exception
  88.        '    MsgBox(ex.Message)
  89.        'End Try
  90.  
  91.    End Sub
  92.  
  93. #End Region
  94.  
  95. #Region " Misc. Date Functions "
  96.  
  97.    ''' <summary>
  98.    ''' Converts a date to the first day's date of the specified <see cref="Date"/> instance,
  99.    ''' and returns the substracted date difference, in days.
  100.    ''' Eg. 28/02/2015 > 01/01/2015 = 31 days in Jan + 28 days in Feb = 59 days
  101.    ''' </summary>
  102.    ''' <param name="date">The <see cref="Date"/> instance.</param>
  103.    ''' <returns>The substracted date difference, in days.</returns>
  104.    Public Function JulianDate(ByVal [date] As Date) As Integer
  105.  
  106.        ' Set the passed date to: 01/01/YYYY (day/month/year)
  107.        Dim dateFirstDay As New Date([date].Year, 1, 1)
  108.  
  109.        ' Return the substracted date difference.
  110.        Return [date].Subtract(dateFirstDay).Days + 1
  111.  
  112.    End Function
  113.  
  114.    ''' <summary>
  115.    ''' Gets the GPS dictionary.
  116.    ''' </summary>
  117.    ''' <param name="datePicker">The <see cref="DateTimePicker"/> instance.</param>
  118.    ''' <returns>IDictionary(Of System.Int32, System.Int32).</returns>
  119.    ''' <exception cref="System.NotImplementedException">
  120.    ''' En este ejemplo no se ha implementado el calendario GPS para el año especificado.
  121.    ''' </exception>
  122.    Private Function GetGPSDictionary(ByVal datePicker As DateTimePicker) As IDictionary(Of Integer, Integer)
  123.  
  124.        Dim year As Integer = Me.Year(datePicker)
  125.        Dim totalDaysInYear As Integer = New Date(year, 1, 1).AddYears(1).Subtract(New Date(year, 1, 1)).Days
  126.        Dim gpsWeeks As IEnumerable(Of Integer)
  127.        Dim result As IDictionary(Of Integer, Integer)
  128.  
  129.        Select Case year
  130.  
  131.            Case 2014
  132.                gpsWeeks = Enumerable.Range(1773 - 1, 53)
  133.  
  134.            Case 2015
  135.                gpsWeeks = Enumerable.Range(1825 - 1, 53)
  136.  
  137.            Case 2016
  138.                gpsWeeks = Enumerable.Range(1877 - 1, 53)
  139.  
  140.            Case Else ' Año desconocido, lanzar excepción.
  141.                Throw New NotImplementedException("En este ejemplo no se ha implementado el calendario GPS para el año especificado.")
  142.  
  143.        End Select
  144.  
  145.        result = New Dictionary(Of Integer, Integer)
  146.        For day As Integer = 0 To (totalDaysInYear - 1)
  147.            result.Add(day, gpsWeeks(DatePart(DateInterval.WeekOfYear,
  148.                                              New DateTime(year, 1, 1).AddDays(day))))
  149.        Next day
  150.  
  151.        Return result
  152.  
  153.    End Function
  154.  
  155. #End Region
  156.  
  157. End Class

Saludos
« Última modificación: 11 Febrero 2015, 15:38 pm por Eleкtro » En línea

rochro

Desconectado Desconectado

Mensajes: 42


Ver Perfil
Re: convertir calendario gregoriano a gps
« Respuesta #4 en: 18 Marzo 2015, 22:27 pm »

Saludos

Hola, habia dejado de lado este tema ya que me estaba dando por vencida pero ahora la idea la tengo algo más clara. Lo que pasa es que las semanas gps tienen una continuidad:

semana gps 1512 --> 28/12/08 al 3/1/09
semana gps 1513 --> 4/1/09 al 10/1/09 

Yo quisiera que el calendario inicie desde la semana 1512 pero no se como relacionarlo con la fecha del calendario gregoriano (el que todos sabemos) ya que se presentan intersecciones como:

semana gps 1564 --> 27/12/09 al 2/1/10
.
.
Lo que se me ocurre es empezar con el 1512 = 28/12/08 + 7 días y así sucesivamente pero no logro saber como hacerlo.

Espero su comprensión y gracias por la atención.
En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
CALENDARIO
Diseño Gráfico
KEVIN091 3 2,431 Último mensaje 24 Agosto 2004, 04:02 am
por Morris
Calendario
Programación Visual Basic
esamper 4 2,164 Último mensaje 12 Enero 2007, 08:57 am
por esamper
Calendario en ASP
.NET (C#, VB.NET, ASP)
eltemplario7 1 4,071 Último mensaje 23 Mayo 2008, 02:54 am
por MANULOMM
Calendario RX
Foro Libre
KarlosVid(ÊÇ) 4 3,280 Último mensaje 22 Febrero 2011, 02:46 am
por urvreak
Calendario
Desarrollo Web
Esprinter 0 2,356 Último mensaje 1 Marzo 2011, 15:26 pm
por Esprinter
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines