Get Correct Date In Milliseconds From Javascript To C# - javascript

I'm using moment to convert a date string to a date object then get the milliseconds of that date and pass it to the server as a query string
the problems is that the milliseconds I get from the javascript when I try to convert it to DateTime in C# it always gives me different date
javascript
function RedirectToOptions() {
var iBranchId = $('#ddl_Branches').val();
var strDate = $('#txt_datepicker').val();
var dtDate = moment(strDate);
var iDate = dtDate.toDate().getTime();
var capitalActionUrl = '#Html.Raw(#Url.Action("Revenue", new {BranchId = "_id_", DateTimeStamp = "_date_" }))';
var branchCapitalUrl = capitalActionUrl.replace("_id_", iBranchId);
var branchCapitalUrl = branchCapitalUrl.replace("_date_", iDate);
window.location.replace(branchCapitalUrl);
}
C#
public ActionResult Revenue(int? BranchId, double? DateTimeStamp)
{
DateTime? date = (DateTimeStamp.HasValue) ? (DateTime?)DateTimeConverter.FromUnixToDateTime(DateTimeStamp.Value) : null;
IEnumerable<RevenueDTO> revenueDTO = _Client.GetRevenue(BranchId, date);
IEnumerable<RevenueViewModel> revenue = ViewModelConverter.RevenueDTOToRevenueViewModel(revenueDTO);
List<BranchDTO> branchesDTO = _Client.GetAllBranches().ToList();
var branches = ViewModelConverter.BranchDTOToBranchesViewModelList(branchesDTO);
ViewBag.Branches = branches;
return View(revenue);
}
Converting to date time
public static DateTime FromUnixToDateTime(double UnixTimeStamp)
{
DateTime dateTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0);
dateTime = dateTime.AddMilliseconds(UnixTimeStamp);
return dateTime;
}
when I try to pass 1/5/2016 (dd/MM/yyyy formatted) when I convert it, it becomes 1/4/2016 for some reason

There is a better way to pass the date object to C# and that is using ordinary ISO 8601 standard format (e.g. 2016-01-01T12:00:00.568Z). If you call toJSON() on your date, the binder in C# should automatically convert it to C# datetime with appropriate time zone.
You will be able to see if you have a timzeone mismatch with you milliseconds in javascript easier as well than dealing with raw millisecond number.
You can read more on it here.

If you are using the epoch, then make sure all your timezones are set in UTC (and convert to local afterwards)... in Javascript:
// ...
var dtDate = moment.utc(strDate);
// ...
And in C#:
// ...
DateTime dateTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
// ...

Related

pass date to c# function from javascript method

I am calling a c# function that returns a FileContentResult. However, the date is not being passed as a parameter to the c# function and always shows as null. what am i missing:
Javascript code:
function exportResponses()
{
window.location = "/Blah/ExportResponse?
questionnaireID=0&clinicID=0&responseStartDate='19/10/2019'";
}
C# function
public FileContentResult ExportResponse(
int questionnaireID = 0,
int clinicID = 0,
DateTime? responseStartDate=null)
{
}
Specific to your problem, you would have to send your date as a string to your Controller method:
public FileContentResult ExportResponse(int questionnaireID = 0, int clinicID = 0, string responseStartDate=null)
And then you can process the string value accordingly in your method.
Try passing the date in the ISO8601 format (i.e. use Date().toISOString() before passing to the view).
Try the following code:
function exportResponses()
{
var startDate = new Date('10/10/2019').toISOString();
window.location = "/SMS/ExportResponse?
questionnaireID=0&clinicID=0&responseStartDate="+startDate ;
}
And in your c# function try parsing parameter responseStartDate into DateTime in your required format.
DateTime startDate = DateTime.ParseExact(responseStartDate, "yyyyMMdd")
try to separate the date to days, month and year, because is not good practice to use "/" in URL variables.
you try something like this :
window.location = "/SMS/ExportResponse?
questionnaireID=0&clinicID=0&day="+startDate.day+"&month="+startDate.month+"&year="+startDate.year

Insert wrong date in MongoDB

I am tring to save dates in my MongoDB table using C#.
Here is a JavaScript logic that send data using Ajax to C# controller
$(function ($, w, d) {
var _user = {}
//var time = moment("2016-04-02", "YYYYMMDD").fromNow()
//var bime = moment().endOf('day').fromNow();
//var crime = moment("20120620", "YYYYMMDD").fromNow();
// document.getElementById('time').innerHTML = time;
var obj = {};
var holidaylist = ["Mar-31-2018", "Apr-01-2018","Apr-04-2018","Apr-07-2018","Apr-08-2018"];
var startdate = new Date("Apr-02-2018");
obj.endDate = "Apr-06-2018";
obj.holidaylist = holidaylist;
obj.NumberOfCount = 9;
CallAjax("POST", '/LeaveManagement/', 'checkleavelogic', obj, onsuccessaddemployee, '');
here is the C# logic that saves the data in MongoDB:
public JsonResult checkLeaveLogic(LeaveLogicModel leaveLogic)
{
string strconnectiomstring = "mongodb://10.10.32.125:27017";
MongoClient Client = new MongoClient(strconnectiomstring);
var DB = Client.GetDatabase("TimeClock");
List<DateTime> leavesDate = new List<DateTime>();
var collection = DB.GetCollection<LeaveLogicModel>("leaves1");
collection.InsertOne(leaveLogic);
}
Now this is the MongoDB table that saves as a previous date.
Here you can see that my StartDate is Apr-02-2018 but it saves as Apr-01-2018 and for all date it is the same.
Can someone tell me where I am wrong?
When you create new dates with just date or date and time, it usually creates them in the same timezone as the program is.
So if you dont specify the timezone, it becomes the timezone the server is in. When you save to Mongo, the Date is serialized to UTC -> zero timezone.
Create the dates with +00:00 timezone and you should have consistent data.
It's a good practice to set your datetimes to UTC, however if you want to convert it, you can use something like this.
var date = DateTime.UtcNow;
TimeZoneInfo.ConvertTime(date, TimeZoneInfo.Local);

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));

Node.js date parameters

I am creating a node.js endpoint that accepts a start date/time and end date/time as parameters. I had been passing them as a string ie:
var body = {
relatedObjectId: "561ee6bbe4b0f25b4aead5c8",
startTime : "11/13/2015 03:00:00PM",
endTime: "11/13/2015 03:30:00PM"
};
and in my service class:
var timeTicket = new TimeTicket();
timeTicket.tutorId = tutorId;
timeTicket.startTime = new Date(startTime);
timeTicket.endTime = new Date(endTime);
timeTicket.save(function(err, timeTicket){
if(err){
return next(err, null);
}
return next(null, timeTicket);
});
However, the cast always fails so i end up with a date in 1970 for startTime and endTime values. It would seem the obvious solution would be to use a UTC format, but what's the right way to do that?
Either use ISO 8601 format as Phil suggested, or simply pass the date as milliseconds (since 1970).
For example, new Date(1447378736842) is the same as new Date("2015-11-13T01:38:56.842Z").
To get the current date in ISO 8601 format, you might do something like this:
var d = new Date();
var n = d.toISOString();
tl;dr version: This is what your body object should look like. I used milliseconds for startTime and an ISO 8601 string for endTime for demonstration purposes. Both are valid.
var body = {
relatedObjectId: "561ee6bbe4b0f25b4aead5c8",
startTime : 1447378736842,
endTime: "2015-11-13T01:38:56.842Z"
};

Convert C# DateTime to Javascript object

I have a c# DateTime passed to the client as:
1980-01-20T00:00:00
How do i convert it to javascript DateTime? I tried doing
var date = new Date(1980-01-20T00:00:00) but this gives me an error
Put it in quotes:
var date = new Date("1980-01-20T00:00:00")
var date = new Date("1980-01-20T00:00:00")
alert(date)
What you need is the amount of miliseconds from 1970:
long epochTicks = new DateTime(1970, 1, 1).Ticks
long unixTime = ((DateTime.UtcNow.Ticks - epochTicks) / TimeSpan.TicksPerSecond);
long javascriptTyme=unixTime*1000;
Thats the value you want to send to javascript

Categories

Resources