ion-datetime: How to get date value without timestamp? - javascript

I'm using ion-datetime in ionic4 using NgModel to bind to a property, however, no matter what options I include in format, I always get the time with the timestamp included. ¿How can I remove timestamp from result so the final value of my property is something like "2019-04-22" instead of "2019-04-22T08:45:41.243-05:00"?
I tried: but, I'm still getting the timestamp
<ion-datetime max="2030" min="2019" [(ngModel)]="mydate" display-format="MMM DD, YYYY"></ion-datetime>
I expect the result to be like: "2019-04-22", but I keep getting: "2019-04-22T08:45:41.243-05:00"

If you want only date then I think split() method might works,beacause value we get from ion-datetime is a string.So we use split method which split string and convert it to an array,and you can get date or time which thing you want with the help of index as follow:
var dateFormat = mydate.split('T')[0];
console.log(dateFormat);
// 2019-04-22

You can format the date with Moment.js.
<ion-datetime displayFormat="MMM DD, YYYY" max="2030" min="2019" [(ngModel)]="mydate" (ionChange)="doSomething(this.mydate)"></ion-datetime>
import * as moment from 'moment';
doSomething(date) {
console.log('date', moment(date).format('YYYY-MM-DD')); // 2019-04-22
}

You can use custom picker options to set custom buttons, it returns an object with all the variables in separate keys, so it makes it easier to edit the way you want it to display
To do so, you would insert this in your ion-datetime
[pickerOptions]="customPickerOptions"
and in your .ts file
this.customPickerOptions = {
buttons: [
{
text: 'Save',
handler: (time) => {
console.log('time', time);
}
},
{
text: 'Cancel',
handler: e => {
modalCtrl.dismiss(e)
}
}
]
}
Hope this helps

<ion-datetime
displayFormat="DD.MM.YYYY"
presentation="date"
[(ngModel)]="date"></ion-datetime>
<div>{{date.split('T')[0]}}</div>
in Ts file
data:any='';

You can use moment.js
in your file.page.html
<ion-datetime [(ngModel)]="mydate" placeholder=""></ion-datetime>
in your file.page.ts
import moment from 'moment';
<!-- to pass data to your API -->
mydate = moment(mydate).format('YYYY-MM-DD');
<!-- to view in console -->
yourFunction(mydate) {
console.log('date', moment(mydate).format('YYYY-MM-DD'));
}
May this answer helps. I understand how frustrating it can be to find the answer we are looking for.

Edit2: toLocaleFormat is not widely accepted. Here is a post on alternatives. You could just split it around the T.
const dateArray = fullDateString.split('T');
if (dateArray.length > 0){
const partYouWant = dateArray[0];
}
Edit: From the Ionic docs
It's also important to note that neither the displayFormat or
pickerFormat can set the datetime value's output, which is the value
that is set by the component's ngModel. The format's are merely for
displaying the value as text and the picker's interface, but the
datetime's value is always persisted as a valid ISO 8601 datetime
string.
Here is a better answer:
const dateObject = new Date(this.mydate);
const dateString = dateObject.toLocaleFormat('%Y-%m-%d');
An input for new Date can be a date string defined as:
String value representing a date. The string should be in a format
recognized by the Date.parse() method (IETF-compliant RFC 2822
timestamps and also a version of ISO8601).
I'm guessing you are trying to access this.mydate in your code.
You have several options, best represented by this stack overflow post.
this.mydate.toLocaleFormat('%Y-%m-%d');
This function will take a Date object and convert it to the string in the format you requested. All the options you can put in the options are here.
There are also plenty of other options shown in the stack overflow post above.

install date-fns by npm i --save date-fns
import {format} from "date-fns"; in your .ts file
let date_x = "2019-11-30T14:42:30.951+08:00";
format(new Date(date_x), "yyyy-MM-dd");
you should get as result in console => '2019-11-29'

This is the best way to get the exactly time
First Create the $event method like this
changeTime(e) {
this.sentTempTime = "";
let hoursMinutes = e.split(':');
this.sentTime = this.formatTime(hoursMinutes);
}
after that create the formatTime() method like this
formatAMPM(date) {
var hours = date[0].toString().split('T'); //22
var minutes = date[1]; //11
var ampm = hours[1] >= 12 ? 'pm' : 'am'; //22 >=12 yes == pm
hours = hours[1] >= 12 ? hours[1] - 12 : hours[1]; //22 >= 12 ? 22-12=10
var strTime = hours + ':' + minutes + ampm;
return strTime;
}
after that you can able to get the time like this 08:15pm

In Ionic 6 you just need the presentation property.
Set it to date and it will only render the date picker, without the time picker.
<ion-datetime presentation="date"></ion-datetime>
See the presentation property in the docs for more details.

Related

momentjs for only time value

I use momentjs to work with date and time
let dateAndTime = moment(component.props.data.value, moment.ISO_8601);
let date = '',
time = '';
if (dateAndTime) {
if (moment(dateAndTime, 'YYYY-MM-DD', true).isValid()) {
date = moment(dateAndTime).format('YYYY-MM-DD');
}
if (moment(dateAndTime, 'HH:mm', true).isValid()) {
time = moment(dateAndTime).format('HH:mm');
}
}
this code works just fine if component.props.data.value contains date and time like 2018-05-22 14:45 or if it contains only date like 2018-05-22. The problem is sometimes component.props.data.value contains only time like 14:45, so moment(component.props.data.value, moment.ISO_8601) doesn't create moment object and code below doesn't execute. Is there any way to handle case only for time?
You can use moment(String, String[]), as the docs says:
If you don't know the exact format of an input string, but know it could be one of many, you can use an array of formats.
This is the same as String + Format, only it will try to match the input to multiple formats.
Your first line of code could be like the following:
let dateAndTime = moment(component.props.data.value, [moment.ISO_8601, 'HH:mm']);

In moment.js, is it possible to have a date-time string and keep the date but change the time?

I'm using moment.js and want to update a date-time string with a new user-entered time. The date has not changed, only the time. There is no timezone change, just that the hour and minute values have possibly been altered.
How would I take a string like this and convert it such that the time is different?
This is would I'd expect:
const dateTimeString = '2017-11-14T16:04:54.0086709-06:00'
const newDateTimeString = (
moment(dateTimeString)
.changeTime('05:20 PM')
.format()
)
// newDateTimeString === '2017-11-14T17:20:00.0086709-06:00'
There is no built in function like changeTime, you can write your own using set.
You can add changeTime using moment.fn
The Moment prototype is exposed through moment.fn. If you want to add your own functions, that is where you would put them.
You can create a temp moment object with your "time to add" value using moment(String, String), then use set(Object(String, Int)) and getters like hours() and minutes().
Here a live sample:
moment.fn.changeTime = function(timeString) {
let m1 = moment(timeString, 'hh:mm A');
return this.set({h: m1.hours(), m: m1.minutes()});
}
const dateTimeString = '2017-11-14T16:04:54.0086709-06:00'
const newDateTimeString = (
moment(dateTimeString)
.changeTime('05:20 PM')
.format()
)
console.log(newDateTimeString);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.2/moment.min.js"></script>
If the user-entered time is formatted as such 13:00 you could do :
const dateTimeString = '2017-11-14T16:04:54.0086709-06:00'
var userInput = "13:20"
const newDateTimeString = (
moment(dateTimeString)
.hours(userInput.split(":")[0])
.minutes(userInput.split(":")[1])
.format()
)
Using https://momentjs.com/docs/#/get-set/hour/ and https://momentjs.com/docs/#/get-set/minute/
If it's formatted with PM and AM system, you could to the same, but with a little bit more of parsing, to know if it's 5.00 AM or PM.
One possible way is to use moment to grab the date and then combine it with your custom time value in another moment() call like so:
const newDateTimeString = (
moment(`${moment(dateTimeString).format('YYYY-MM-DD')} 05:20 PM`)
.format()
)

Property date to String for parsing

I'm trying to insert creation date into table view in specific format.
Now it's like DD/MM/YYYY HH:MM:ss and I want it like DD/MM/YYYY.
YAHOO.Bubbling.fire("registerRenderer", {
propertyName: "test:date",
renderer: function functionPrice(record, label){
var jsNode = record.jsNode,
properties = jsNode.properties;
var rawDate = properties['test:date'];
var date= rawDate().toString().substring(0, 11);
return '<div id="attachments">' + date + '</div>';
}
});
In this case, column contains [Object obj.
I also tried convert it to toISOString but it returns Invalid Date.
Column is set like d:date but output is d:datetime and I don't know why.
Thank you.
If your date format is fixed, this is a safe way to create a Date instance:
var value = "31/12/2017 00:00:00";
var dd = value.substring(0,2);
var mm = value.substring(3,5);
var yyyy = value.substring(6,10);
var d = new Date(yyyy, mm - 1, dd); // Sun Dec 31 2017 00:00:00 GMT+0800 (+08)
To change dates the dates displayed in the date picker control, but this file may not exist in your environment. See if the following file exists:
<alfresco home>\tomcat\shared\classes\alfresco\web-extension\site-webscripts\org\alfresco\components\form\form.get_en.properties
If it doesn’t exist, copy it from here (create the form folder if necessary):
<alfresco home>\tomcat\webapps\share\WEB-INF\classes\alfresco\site-webscripts\org\alfresco\components\form\form.get_en.properties
Open the form.get_en.properties file for editing. Search for “form-control.date-picker” to find the proper properties to change (we found four values on a recent installation).
Restart Alfresco to make the changes take effect.

adding one day to my date [duplicate]

I'm working with a date in this format: yyyy-mm-dd.
How can I increment this date by one day?
Something like this should do the trick:
String dt = "2008-01-01"; // Start date
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar c = Calendar.getInstance();
c.setTime(sdf.parse(dt));
c.add(Calendar.DATE, 1); // number of days to add
dt = sdf.format(c.getTime()); // dt is now the new date
UPDATE (May 2021): This is a really outdated answer for old, old Java. For Java 8 and above, see https://stackoverflow.com/a/20906602/314283
Java does appear to be well behind the eight-ball compared to C#. This utility method shows the way to do in Java SE 6 using the Calendar.add method (presumably the only easy way).
public class DateUtil
{
public static Date addDays(Date date, int days)
{
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DATE, days); //minus number would decrement the days
return cal.getTime();
}
}
To add one day, per the question asked, call it as follows:
String sourceDate = "2012-02-29";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date myDate = format.parse(sourceDate);
myDate = DateUtil.addDays(myDate, 1);
java.time
On Java 8 and later, the java.time package makes this pretty much automatic. (Tutorial)
Assuming String input and output:
import java.time.LocalDate;
public class DateIncrementer {
static public String addOneDay(String date) {
return LocalDate.parse(date).plusDays(1).toString();
}
}
I prefer to use DateUtils from Apache. Check this http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/time/DateUtils.html. It is handy especially when you have to use it multiple places in your project and would not want to write your one liner method for this.
The API says:
addDays(Date date, int amount) : Adds a number of days to a date returning a new object.
Note that it returns a new Date object and does not make changes to the previous one itself.
SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd" );
Calendar cal = Calendar.getInstance();
cal.setTime( dateFormat.parse( inputString ) );
cal.add( Calendar.DATE, 1 );
Construct a Calendar object and call add(Calendar.DATE, 1);
Java 8 added a new API for working with dates and times.
With Java 8 you can use the following lines of code:
// parse date from yyyy-mm-dd pattern
LocalDate januaryFirst = LocalDate.parse("2014-01-01");
// add one day
LocalDate januarySecond = januaryFirst.plusDays(1);
Take a look at Joda-Time (https://www.joda.org/joda-time/).
DateTimeFormatter parser = ISODateTimeFormat.date();
DateTime date = parser.parseDateTime(dateString);
String nextDay = parser.print(date.plusDays(1));
Please note that this line adds 24 hours:
d1.getTime() + 1 * 24 * 60 * 60 * 1000
but this line adds one day
cal.add( Calendar.DATE, 1 );
On days with a daylight savings time change (25 or 23 hours) you will get different results!
you can use Simple java.util lib
Calendar cal = Calendar.getInstance();
cal.setTime(yourDate);
cal.add(Calendar.DATE, 1);
yourDate = cal.getTime();
Date today = new Date();
SimpleDateFormat formattedDate = new SimpleDateFormat("yyyyMMdd");
Calendar c = Calendar.getInstance();
c.add(Calendar.DATE, 1); // number of days to add
String tomorrow = (String)(formattedDate.format(c.getTime()));
System.out.println("Tomorrows date is " + tomorrow);
This will give tomorrow's date. c.add(...) parameters could be changed from 1 to another number for appropriate increment.
If you are using Java 8, then do it like this.
LocalDate sourceDate = LocalDate.of(2017, Month.MAY, 27); // Source Date
LocalDate destDate = sourceDate.plusDays(1); // Adding a day to source date.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); // Setting date format
String destDate = destDate.format(formatter)); // End date
If you want to use SimpleDateFormat, then do it like this.
String sourceDate = "2017-05-27"; // Start date
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar calendar = Calendar.getInstance();
calendar.setTime(sdf.parse(sourceDate)); // parsed date and setting to calendar
calendar.add(Calendar.DATE, 1); // number of days to add
String destDate = sdf.format(calendar.getTime()); // End date
Since Java 1.5 TimeUnit.DAYS.toMillis(1) looks more clean to me.
SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd" );
Date day = dateFormat.parse(string);
// add the day
Date dayAfter = new Date(day.getTime() + TimeUnit.DAYS.toMillis(1));
long timeadj = 24*60*60*1000;
Date newDate = new Date (oldDate.getTime ()+timeadj);
This takes the number of milliseconds since epoch from oldDate and adds 1 day worth of milliseconds then uses the Date() public constructor to create a date using the new value. This method allows you to add 1 day, or any number of hours/minutes, not only whole days.
In Java 8 simple way to do is:
Date.from(Instant.now().plusSeconds(SECONDS_PER_DAY))
It's very simple, trying to explain in a simple word.
get the today's date as below
Calendar calendar = Calendar.getInstance();
System.out.println(calendar.getTime());// print today's date
calendar.add(Calendar.DATE, 1);
Now set one day ahead with this date by calendar.add method which takes (constant, value). Here constant could be DATE, hours, min, sec etc. and value is the value of constant. Like for one day, ahead constant is Calendar.DATE and its value are 1 because we want one day ahead value.
System.out.println(calendar.getTime());// print modified date which is tomorrow's date
Thanks
startCalendar.add(Calendar.DATE, 1); //Add 1 Day to the current Calender
In java 8 you can use java.time.LocalDate
LocalDate parsedDate = LocalDate.parse("2015-10-30"); //Parse date from String
LocalDate addedDate = parsedDate.plusDays(1); //Add one to the day field
You can convert in into java.util.Date object as follows.
Date date = Date.from(addedDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
You can formate LocalDate into a String as follows.
String str = addedDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
With Java SE 8 or higher you should use the new Date/Time API
int days = 7;
LocalDate dateRedeemed = LocalDate.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/YYYY");
String newDate = dateRedeemed.plusDays(days).format(formatter);
System.out.println(newDate);
If you need to convert from java.util.Date to java.time.LocalDate, you may use this method.
public LocalDate asLocalDate(Date date) {
Instant instant = date.toInstant();
ZonedDateTime zdt = instant.atZone(ZoneId.systemDefault());
return zdt.toLocalDate();
}
With a version prior to Java SE 8 you may use Joda-Time
Joda-Time provides a quality replacement for the Java date and time
classes and is the de facto standard date and time library for Java
prior to Java SE 8
int days = 7;
DateTime dateRedeemed = DateTime.now();
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/uuuu");
String newDate = dateRedeemed.plusDays(days).toString(formatter);
System.out.println(newDate);
Apache Commons already has this DateUtils.addDays(Date date, int amount) http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/time/DateUtils.html#addDays%28java.util.Date,%20int%29 which you use or you could go with the JodaTime to make it more cleaner.
Just pass date in String and number of next days
private String getNextDate(String givenDate,int noOfDays) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Calendar cal = Calendar.getInstance();
String nextDaysDate = null;
try {
cal.setTime(dateFormat.parse(givenDate));
cal.add(Calendar.DATE, noOfDays);
nextDaysDate = dateFormat.format(cal.getTime());
} catch (ParseException ex) {
Logger.getLogger(GR_TravelRepublic.class.getName()).log(Level.SEVERE, null, ex);
}finally{
dateFormat = null;
cal = null;
}
return nextDaysDate;
}
If you want to add a single unit of time and you expect that other fields to be incremented as well, you can safely use add method. See example below:
SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
Calendar cal = Calendar.getInstance();
cal.set(1970,Calendar.DECEMBER,31);
System.out.println(simpleDateFormat1.format(cal.getTime()));
cal.add(Calendar.DATE, 1);
System.out.println(simpleDateFormat1.format(cal.getTime()));
cal.add(Calendar.DATE, -1);
System.out.println(simpleDateFormat1.format(cal.getTime()));
Will Print:
1970-12-31
1971-01-01
1970-12-31
Use the DateFormat API to convert the String into a Date object, then use the Calendar API to add one day. Let me know if you want specific code examples, and I can update my answer.
Try this method:
public static Date addDay(int day) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
calendar.add(Calendar.DATE, day);
return calendar.getTime();
}
It's simple actually.
One day contains 86400000 milliSeconds.
So first you get the current time in millis from The System by usingSystem.currentTimeMillis() then
add the 84000000 milliSeconds and use the Date Class to generate A date format for the milliseconds.
Example
String Today = new Date(System.currentTimeMillis()).toString();
String Today will be 2019-05-9
String Tommorow = new Date(System.currentTimeMillis() + 86400000).toString();
String Tommorow will be 2019-05-10
String DayAfterTommorow = new Date(System.currentTimeMillis() + (2 * 86400000)).toString();
String DayAfterTommorow will be 2019-05-11
You can use this package from "org.apache.commons.lang3.time":
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date myNewDate = DateUtils.addDays(myDate, 4);
Date yesterday = DateUtils.addDays(myDate, -1);
String formatedDate = sdf.format(myNewDate);
If you are using Java 8, java.time.LocalDate and java.time.format.DateTimeFormatter can make this work quite simple.
public String nextDate(String date){
LocalDate parsedDate = LocalDate.parse(date);
LocalDate addedDate = parsedDate.plusDays(1);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-mm-dd");
return addedDate.format(formatter);
}
The highest voted answer uses legacy java.util date-time API which was the correct thing to do in 2009 when the question was asked. In March 2014, java.time API supplanted the error-prone legacy date-time API. Since then, it is strongly recommended to use this modern date-time API.
I'm working with a date in this format: yyyy-mm-dd
You have used the wrong letter for the month, irrespective of whether you are using the legacy parsing/formatting API or the modern one. The letter m is used for minute-of-hour and the correct letter for month-of-year is M.
yyyy-MM-dd is the default format of java.time.LocalDate
The java.time API is based on ISO 8601 standards and therefore it does not require specifying a DateTimeFormatter explicitly to parse a date-time string if it is already in ISO 8601 format. Similarly, the toString implementation of a java.time type returns a string in ISO 8601 format. Check LocalDate#parse and LocalDate#toString for more information.
Ways to increment a local date by one day
There are three options:
LocalDate#plusDays(long daysToAdd)
LocalDate#plus(long amountToAdd, TemporalUnit unit): It has got some additional capabilities e.g. you can use it to increment a local date by days, weeks, months, years etc.
LocalDate#plus(TemporalAmount amountToAdd): You can specify a Period (or any other type implementing the TemporalAmount) to add.
Demo:
import java.time.Instant;
import java.time.LocalDate;
import java.time.Period;
import java.time.temporal.ChronoUnit;
public class Main {
public static void main(String[] args) {
// Parsing
LocalDate ldt = LocalDate.parse("2020-10-20");
System.out.println(ldt);
// Incrementing by one day
LocalDate oneDayLater = ldt.plusDays(1);
System.out.println(oneDayLater);
// Alternatively
oneDayLater = ldt.plus(1, ChronoUnit.DAYS);
System.out.println(oneDayLater);
oneDayLater = ldt.plus(Period.ofDays(1));
System.out.println(oneDayLater);
String desiredString = oneDayLater.toString();
System.out.println(desiredString);
}
}
Output:
2020-10-20
2020-10-21
2020-10-21
2020-10-21
2020-10-21
How to switch from the legacy to the modern date-time API?
You can switch from the legacy to the modern date-time API using Date#toInstant on a java-util-date instance. Once you have an Instant, you can easily obtain other date-time types of java.time API. An Instant represents a moment in time and is independent of a time-zone i.e. it represents a date-time in UTC (often displayed as Z which stands for Zulu-time and has a ZoneOffset of +00:00).
Demo:
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.Date;
public class Main {
public static void main(String[] args) {
Date date = new Date();
Instant instant = date.toInstant();
System.out.println(instant);
ZonedDateTime zdt = instant.atZone(ZoneId.of("Asia/Kolkata"));
System.out.println(zdt);
OffsetDateTime odt = instant.atOffset(ZoneOffset.of("+05:30"));
System.out.println(odt);
// Alternatively, using time-zone
odt = instant.atZone(ZoneId.of("Asia/Kolkata")).toOffsetDateTime();
System.out.println(odt);
LocalDateTime ldt = LocalDateTime.ofInstant(instant, ZoneId.of("Asia/Kolkata"));
System.out.println(ldt);
// Alternatively,
ldt = instant.atZone(ZoneId.of("Asia/Kolkata")).toLocalDateTime();
System.out.println(ldt);
}
}
Output:
2022-11-12T12:52:18.016Z
2022-11-12T18:22:18.016+05:30[Asia/Kolkata]
2022-11-12T18:22:18.016+05:30
2022-11-12T18:22:18.016+05:30
2022-11-12T18:22:18.016
2022-11-12T18:22:18.016
Learn more about the modern Date-Time API from Trail: Date Time.
Let's clarify the use case: You want to do calendar arithmetic and start/end with a java.util.Date.
Some approaches:
Convert to string and back with SimpleDateFormat: This is an inefficient solution.
Convert to LocalDate: You would lose any time-of-day information.
Convert to LocalDateTime: This involves more steps and you need to worry about timezone.
Convert to epoch with Date.getTime(): This is efficient but you are calculating with milliseconds.
Consider using java.time.Instant:
Date _now = new Date();
Instant _instant = _now.toInstant().minus(5, ChronoUnit.DAYS);
Date _newDate = Date.from(_instant);
You can do this just in one line.
e.g to add 5 days
Date newDate = Date.from(Date().toInstant().plus(5, ChronoUnit.DAYS));
to subtract 5 days
Date newDate = Date.from(Date().toInstant().minus(5, ChronoUnit.DAYS));

Javascript - Convert ####-##-## to Epoch time

Is there a way to take a date object from a HTML object in the format of ####-##-## and convert it to epoch time. For example, the user inputs the value of August 12, 2012 which shows as 2012-08-12 when I print out the .val() of it, and I need to get this in Epoch time.
EDIT
Code to date:
if (hvStartDate == "") {
hvStartDate = "start"
}
else {
console.log($("#hv-start-date").val()); // => 2012-08-20
hvStartDate = new Date($("#hv-start-date").val()).getTime(); // => NaN
}
if (hvEndDate == "") {
hvEndDate = "end"
}
else {
hvEndDate = new Date($("#hv-end-date").val()).getTime(); // => NaN
}
var myTmp = new Date("2012-08-20");
console.log(myTmp.getTime()); // => NaN
Javascript's Date built-in allows you to pass a date string into its constructor, giving you a Date based on that string. From there, calling getTime( ) will give you the epoch time.
new Date($('.user-value').val()).getTime(); // => epoch time
new Date('2012-08-12').getTime(); // 1344729600000
Caveat: Beware of locale strings and locale-specific date formatting (for example, the position of days and months switch depending on locale).
EDIT: Based on your code in the comment below, here's what you need to do. Notice that you have to instantiate a new Date Object before calling getTime():
if (hvStartDate == "") {
hvStartDate = "start"
}
else {
hvStartDate = new Date($("#hv-start-date").val()).getTime();
}
Simply use the getTime() function. It returns the number of milliseconds since Epoch :
var msSinceEpoch = myDate.getTime();
Complete Date reference at MDN : https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date
EDIT : if you have to parse it too, you may :
use new Date(theString) if it has the good format
set yourself the different date fields (see reference) after having parsed it
use a date parsing library. I use this one : http://www.datejs.com/ which is very powerful for all date parsing, computing and formating.

Categories

Resources